44 lines
947 B
TypeScript
44 lines
947 B
TypeScript
export class EventTarget {
|
|
listeners: {
|
|
[type: string]: Function[]
|
|
}
|
|
|
|
constructor() {
|
|
this.listeners = {};
|
|
}
|
|
|
|
addEventListener(type: string, callback: Function) {
|
|
if (!(type in this.listeners)) {
|
|
this.listeners[type] = [];
|
|
}
|
|
this.listeners[type].push(callback);
|
|
};
|
|
|
|
removeEventListener(type: string, callback: Function) {
|
|
if (!(type in this.listeners)) {
|
|
return;
|
|
}
|
|
const stack = this.listeners[type];
|
|
for (var i = 0, l = stack.length; i < l; i++) {
|
|
if (stack[i] === callback){
|
|
stack.splice(i, 1);
|
|
return;
|
|
}
|
|
}
|
|
};
|
|
|
|
dispatchEvent(event: Event) {
|
|
if (!(event.type in this.listeners)) {
|
|
return true;
|
|
}
|
|
|
|
const stack = this.listeners[event.type].slice();
|
|
|
|
for (let i = 0, l = stack.length; i < l; i++) {
|
|
stack[i].call(this, event);
|
|
if (event.cancelBubble) return;
|
|
}
|
|
return !event.defaultPrevented;
|
|
};
|
|
|
|
} |