写一个EventEmitter,实现on(监听事件)、emit(触发事件)、off(清除监听事件)、once(为事件注册单次监听器)以上功能:
class EventEmitter {
constructor() {
this.events = {};
}
on(eventName, callback) {
if (!this.events[eventName]) {
this.events[eventName] = [callback];
} else {
this.events[eventName].push(callback);
}
}
emit(eventName, ...args) {
if (this.events[eventName]) {
this.events[eventName].forEach(fn => {
fn.apply(this, args);
})
}
}
off(eventName, callback) {
this.events[eventName] = this.events[eventName].filter(fn => fn != callback);
}
once(eventName, callback) {
const fn = () => {
callback();
this.off(eventName, fn);
}
this.on(eventName, fn);
}
}
const emitter = new EventEmitter();
function onHandler(name) {
console.log(`hello ${name}!`);
}
function onceHandler(name, msg) {
console.log(`你好 ${name} ${msg}!`);
}
emitter.on("on", onHandler);
emitter.once("once", onceHandler);
emitter.emit("on", "今天星期一");
emitter.emit("on", "上课");
emitter.emit("once", "上课");
emitter.off("on", onHandler);
emitter.emit("on", "今天星期一");
emitter.emit("once", "上课");
|