其他分享
首页 > 其他分享> > 自定义事件派发机制

自定义事件派发机制

作者:互联网

简单实现事件的派发和监听

export default class EventEmitter {
  private events: any;

  constructor() {
    this.events = {};
  }

  /**
   * 监听 event 事件,触发时调用 callback 函数
   * @param event 
   * @param callback 
   * @returns 
   */
  on(event: string, callback: Function) {
    let callbacks = this.events[event] || [];
    callbacks.push(callback);
    this.events[event] = callbacks;
    return this;
  }

  /**
   * 停止监听 event 事件
   * @param event 
   * @param callback 
   * @returns 
   */
  off(event: string, callback: Function) {
    if (event === "*") {
      this.events = {};
      return this;
    }
    let callbacks = this.events[event];
    this.events[event] =
      callbacks && callbacks.filter((fn: Function) => fn !== callback);
    return this;
  }

  /**
   * 触发事件,并把参数传给事件的处理函数
   * @param event 
   * @param args 
   * @returns 
   */
  emit(event: string, ...args: any) {
    const callbacks = this.events[event];
    callbacks && callbacks.forEach((fn: Function) => fn.apply(null, args));
    return this;
  }
}

 

标签:Function,自定义,callback,派发,param,event,callbacks,机制,events
来源: https://www.cnblogs.com/hyt09/p/15030151.html