类式定义方式
class EventEmitter {
handlers = {
};
on(type, handler, once = false) {
if (!this.handlers[type]) {
this.handlers[type] = [];
}
if (!this.handlers[type].includes(handler)) {
this.handlers[type].push(handler);
handler.once = once;
}
}
once(type, hanlder) {
this.on(type, hanlder, true);
}
off(type, handler) {
if (this.handlers[type]) {
this.handlers[type] = this.handlers[type].filter((h) => h !== handler);
}
}
trigger(type) {
if (this.handlers[type]) {
this.handlers[type].forEach((handler) => {
handler.call(this);
if (handler.once) {
this.off(type, handler);
}
});
}
}
}
测试和打印
const ev = new EventEmitter();
function handler1() {
console.log("handler1");
}
function handler2() {
console.log("handler2");
}
function handler3() {
console.log("handler3");
}
ev.on("test", handler1);
ev.on("test", handler2);
ev.on("test", handler3);
ev.trigger("test");
ev.trigger("test");
输出如下: