一个简单的EventEmitter模式的实现
class EventEmitter {
constructor() {
this.listeners = {};
}
on(key, cb) {
if (!this.listeners[key]) {
this.listeners[key] = [];
}
this.listeners[key].push(cb);
}
emit(key, args) {
const cbs = this.listeners[key] || [];
cbs.forEach((cb) => {
cb.apply(this, args);
});
}
removeListener(key, listener) {
const cbs = this.listeners[key] || [];
const idx = cbs.indexOf(listener);
if (idx === -1) {
return;
}
cbs.splice(idx, 1);
}
}
/****************************************分割线****************************************/
// 用例1:
const emitter = new EventEmitter();
emitter.on("a", () => {
console.log("1");
});
emitter.on("a", () => {
console.log("2");
});
emitter.on("b", () => {
console.log("12");
});
console.log("我是一个断点打印, 时间:15:16:12", emitter, emitter.listeners);
emitter.emit("a");
Tags: