EventEmitter
class EventEmitterDemo {
constructor() {
this.events = {}; // 映射事件名和处理函数
}
// 将处理函数添加到事件的回调队列后
on(name, cb) {
if (!this.events[name]) {
this.events[name] = [];
}
this.events[name].push(cb);
}
// 将处理函数添加到事件的回调队列前
prependListener(name, cb) {
if (!this.events[name]) {
this.events[name] = [];
}
this.events[name].unshift(cb);
}
// 触发事件,执行回调函数
emit(name, args = "") {
for (let cb of this.events[name]) {
cb(args);
}
}
// 移除某一个回调函数
off(name, cb) {
let cbs = this.events[name];
let cbIndex = cbs.indexOf(cb);
if (cbIndex !== -1) {
this.events[name].splice(cbIndex, 1);
}
}
// 为指定事件注册一个单次监听器,监听器至多只会触发一次,触发后立即解除该监听器
once(name, cb) {
let onceCb = (...argvs) => {
cb(...argvs);
this.off(name, onceCb);
};
this.on(name, onceCb);
}
}
// const EventEmitter = require('events');
let event = new EventEmitterDemo();
let demoFunc = function () {
// 绑定事件和处理函数
console.log("demo boom!");
};
let demo2Func = function () {
console.log("demo2 boom!");
};
let demo3Func = function () {
console.log("demo3 boom!");
};
event.once("demo", demoFunc);
event.on("demo", demo2Func);
event.prependListener("demo", demo3Func);
event.off("demo", demo2Func);
console.log("set fire to demo");
setTimeout(function () {
event.emit("demo");
}, 1000);
setTimeout(function () {
event.emit("demo");
}, 2000);
手写 eventbus,参考