1、代码
class EventBus { constructor(){ this.events = {}; } on(event,handler){ if(!this.events[event]){ this.events[event] = []; } this.events[event].push(handler); } emit(event,data){ if (this.events[event]){ this.events[event].forEach((handler)=>{ handler(data); }) } } off(event,handler){ if (this.events[event]) { this.events[event] = this.events[event].filter(h=>h !== handler) } } remove(event){ delete this.events[event] } } export { EventBus }
2、使用方法
const $bus = new EventBus();
//订阅
$bus.on("greet", func)
//发布
$bus.emit("greet", "word");//取消订阅
$bus.remove("greet",func);
//删除订阅
$bus.remove("greet");function func(arg){
console.log(arg)
}
标签:订阅,bus,JavaScript,greet,events,发布,handler,event From: https://www.cnblogs.com/jzm2842688813/p/18249133