
/**
 * Simple event subscrible class
 */
export default class EventEmitter {
  listeners: any;
  constructor() {
    this.listeners = {};
  }

  /**
   * Subscribe event.
   */
  on(evt: string, func: Function) {
    if (!evt) return;
    if (!this.listeners[evt]) {
      this.listeners[evt] = [];
    }
    this.listeners[evt].push(func);
  }

  /**
   * Unsubscribe event.
   */
  un(evt: string, func: Function) {
    if (!evt) return;
    if (!this.listeners[evt]) return;
    var index = this.listeners[evt].indexOf(func);
    if (index < 0) return;
    this.listeners[evt].splice(index, 1);
  }

  /**
   * Trigger event.
   */
  trigger(evt : string, ...args) {
    //console.log(this, 'trigger:', evt)
    if (!evt) return;
    if (!this.listeners[evt]) return;
    var self = this;
    this.listeners[evt].forEach(func => func(self, ...args));
  }


  /**
   * 防止内存泄漏
   */
  destroy(){
    this.listeners = {};
  }

}
