41

How to set the EventTarget of a Event.

var myObj = {foo: 'bar'};
var event = new Event('eventName');
event.target = myObj;

Will result in the following error:

Uncaught TypeError: Cannot set property target of #<Event> which has only a getter

Edit:

I want to write something like this, where my class will be the target:

class MyClass {

  constructor() {
    this.listeners = {};
  }

  addEventListener(type, callback) {
    if (!(type in this.listeners)) {
      this.listeners[type] = [];
    }
    this.listeners[type].push(callback);
  }

  removeEventListener() {
    if (!(type in this.listeners)) {
      return;
    }
    var stack = this.listeners[type];
    for (var i = 0, l = stack.length; i < l; i++) {
      if (stack[i] === callback) {
        stack.splice(i, 1);
        return this.removeEventListener(type, callback);
      }
    }
  }

  dispatchEvent(event) {
    if (!(event.type in this.listeners)) {
      return;
    }
    var stack = this.listeners[event.type];
    event.target = this;
    for (var i = 0, l = stack.length; i < l; i++) {
      stack[i].call(this, event);
    }
  }

}

let myInstance = new MyClass();
let event = new Event('eventName');
myInstance.dispatchEvent();

More info: https://developer.mozilla.org/en/docs/Web/API/EventTarget

2
  • 1
    I may be misunderstanding but the EventTarget is normally automatically set by the browser as the element upon which the event was fired/triggered. What is it that you're trying to do? It feels, from the limited information in your question, that you should be using EventTarget.addEventListener() but I'm very, very unsure of your intent so far. Commented May 26, 2016 at 9:16
  • If this is for a real, established DOM event, then new Event(eventName, { target: ... }) is your answer. If this is not a real event, i.e. one you invented yourself, don't use Event, dispatch a CustomEvent and put whatever you want in the detail property. Commented Jul 20 at 22:16

3 Answers 3

46

Okay - I just had a brainwave and so here's another answer for you that's very naughty and might just work. (worked for me ;)

Instead of doing event.target = myObj, you could try:

Object.defineProperty(event, 'target', {writable: false, value: myObj});

I may be wrong here, but I think what happens is that the new target property hides the original one. It doesn't work the same way as the browser internal event dispatching, and the browser event handling code will almost certainly ignore it, but it might just be enough to fool javascript code that relies on Event.target.

Also, be careful to test it in different browsers, as some browsers might define Event.target as a non-configurable property.

3
  • 12
    This is perfect for unit-testing, thanks for sharing :)
    – danwellman
    Commented May 15, 2018 at 10:26
  • is it seriously this difficult to do unit-testing of a component in JavaScript in 2023? Commented Mar 12, 2023 at 16:42
  • Bravo, I have used this approach before to manipulate the DOM in some unit tests, never once did I consider this as a great approach for events. I just successfully mimicked a copy and paste unit test, firing both a paste and input event successfully now. Thank you!
    – Willie
    Commented Aug 2 at 13:21
21

Regarding your edit, it markedly changes the question. The answer now is: Don't use CustomEvent, you're trying to use it for something other than its intended purpose. Just use your own object, as you never dispatch the event to a DOM element.


It's set automatically when you dispatch the event:

targetElement.dispatchEvent(event);

If you want to include custom data other than the element with the event, simply add it as a property:

event.data = myObj;

Example:

"use strict";
var div = document.getElementById("target");

div.addEventListener(
  "eventName",
  function(e) {
    console.log("e.target:", e.target);
    console.log("e.data:", e.data);
  },
  false
);

var myObj = {foo: "bar"};
var event = new Event("eventName");
event.data = myObj;
div.dispatchEvent(event);
<div id="target"></div>

11
  • I don't want an DOMElement to be the EventTarget. Instead it should be an Object of my choice.
    – HaNdTriX
    Commented May 26, 2016 at 9:22
  • 1
    @HaNdTriX: Your edit changes the question hugely, almost enough that it should be rolled back. (Fundamentally changing a question after it has answers isn't allowed on SO. I think this just barely slips by.) I've edited the answer to address the new question. Commented May 26, 2016 at 9:24
  • I never mentioned DOM Elements. I tried to reduce my Problem to the essential part. In Javascript there are many examples where an Event has a target wich is not a DOM Element. (e.g.: Notification Events) Sorry to be unclear about this.
    – HaNdTriX
    Commented May 26, 2016 at 9:27
  • @HaNdTriX: You linked to a web-specific interface and used new Event in the code. That's quite clearly a question about DOM events. Your updated question is about your own pub/sub system. Anyway, the answer is: Don't use CustomEvent (or Event). Commented May 26, 2016 at 9:30
  • 1
    @Guntram - Works for me without being in the DOM. Tested in Chromium-based browsers (Chrome, Edge, Opera, etc.) Firefox, and iOS Safari. Commented Jul 14, 2022 at 16:31
1

It's 1 year, 9 months on from your original question and I want to do exactly this with exactly the same code, from exactly the same place. I know exactly why you want to do this, it's because EventTarget isn't a constructable object in all browsers yet. And it would appear that no, there is no real solution to your problem.

In case anybody else has this problem and stumbles across this page, the solution is to not rely on Event.target. You can create a custom event and dispatch it like this:

var myeventtarget = new MyClass();

var ev = new CustomEvent('myevent', {
    detail: {
        target: myeventtarget
    }});

myeventtarget.dispatchEvent(ev);

Then, in the event handler, the target can be accessed with:

var event_handler = function(ev) {
    var target = ev.detail.target;
    alert(target);
}

It's a truly ugly syntax but it looks like the only 'proper' way this can be accomplished right now. Now, if you ignore older browsers, I know that in the newer Firefox and Chrome browsers, you can implement MyClass like this:

class MyClass extends EventTarget {
    constructor() {
        super()
    }
}

I haven't tested whether the event target is set when dispatched on an object of type MyClass given the above definition, but if not, it might be worth suggesting it as a change to the DOM Living Standard since it clearly makes sense. (the spec doesn't currently appear to suggest that it should work)

Lastly, can I caution you against using the javascript EventTarget code you are using without checking it works properly first. I found that it breaks when you hand it an EventListener object. It also appends a duplicate event if you hand in the same event twice to addEventListener(), while the DOM Living Standard clearly states it must not do so. It's fortunately very easy to fix these issues. You need to change stack[i].call(this, event); to:

if (stack[i].handleEvent) stack[i].handleEvent(event);
        else stack[i].call(this, event);

And add the following:

var stack = this.listeners[type];
for (var i = 0, l = stack.length; i < l; i++) {
    if (stack[i] === callback){
        return;
    }
}

before this.listeners[type].push(callback);

Other problems are that addEventListener() doesn't simply return if you hand it a null callback (another easy fix), and obviously it doesn't allow options to be handed in to it. (but decide whether you really need this feature)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.