关于javascript:发布订阅模式

公布订阅模式
class EventEmitter {
  constructor() {
     this.cache = {}
  }
  
  // 注册事件
  $on(eventType, fn) {
    // 增加事件
    this.cache[eventType] = this.cache[eventType] || [];
    this.cache[eventType].push(fn);
  }
  
  // 触发事件
  $emit(eventType) {
    if(this.cache[eventType]) {
        this.cache[eventType].forEach(handle=>{
            handle();
        })
    }
  }
}

// 测试

let eventEmitter = new EventEmitter();
function f(){
   console.log("Jason");
}
eventEmitter.$on('click' f);
eventEmitter.$emit('click');        // Jason

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理