js & Event Bus
global event handler (broadcast / trigger / emit / listen )
// 实现一个 EventBus类,这个类包含以下方法:
// on(监听事件,该事件可以被触发多次)
// once(也是监听事件,但只能被触发一次)
// fire(触发指定的事件)
// off(移除指定事件的某个回调方法或者所有回调方法)
// 解题思路: class 存储 evnets, 按类型分别处理 once
class EventBus {
constructor() {
this.eventBus = {};
}
on(name, callback) {
this.eventBus[name] = {
callback,
once: false,
};
}
once(name, callback) {
this.eventBus[name] = {
callback,
once: true,
};
}
off(name) {
let keys = Object.keys(this.eventBus);
if (keys.includes(name)) {
delete this.eventBus[name];
}
}
fire(name, person) {
// dispatchEvent
let keys = Object.keys(this.eventBus);
if (keys.includes(name)) {
let fun = this.eventBus[name].callback;
let once = this.eventBus[name].once;
// pass data
fun(person);
if (once) {
delete this.eventBus[name];
}
}
}
}
demo
const event = new EventBus();
const log = console.log;
event.on("drink", (person) => {
log(person + "喝水");
});
event.on("eat", (person) => {
log(person + "吃东西");
});
event.once("buy", (person) => {
log(person + "买东西");
});
event.fire("drink", "我");
// 我喝水
event.fire("drink", "我");
// 我喝水
event.fire("eat", "其它人");
// 其它人吃东西
event.fire("eat", "其它人");
// 其它人吃东西
event.fire("buy", "其它人");
//其它人买东西
event.fire("buy", "其它人");
//这里不会再次触发buy事件,因为once只能触发一次
event.off("eat") //移除eat事件
event.fire("eat", "其它人");
//这里不会触发eat事件,因为已经移除了
https://repl.it/@xgqfrms/Event-Bus