mdn中EventTarget的简单实现代码
let EventTarget = function () {
this.listeners = {};
}
EventTarget.prototype.listeners = null;
EventTarget.prototype.addEventListener = function (type, callback) {
if (!(type in this.listeners)) {
this.listeners[type] = [];
}
this.listeners[type].push(callback);
};
EventTarget.prototype.removeEventListener = function (type, callback) {
if (!(type in this.listeners)) {
return;
}
let stack = this.listeners[type];
for (let i = 0, l = stack.length; i < l; i++) {
if (stack[i] === callback) {
stack.splice(i, 1);
return this.removeEventListener(type, callback);
}
}
};
EventTarget.prototype.dispatchEvent = function (event) {
if (!(event.type in this.listeners)) {
return;
}
let stack = this.listeners[event.type];
event.target = this;
for (let i = 0, l = stack.length; i < l; i++) {
stack[i].call(this, event);
}
};
标签:实现,event,EventTarget,callback,listeners,简单,type,stack
From: https://www.cnblogs.com/xyzJoker/p/18630418