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
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 usingEventTarget.addEventListener()
but I'm very, very unsure of your intent so far.new Event(eventName, { target: ... })
is your answer. If this is not a real event, i.e. one you invented yourself, don't useEvent
, dispatch aCustomEvent
and put whatever you want in thedetail
property.