在 ES6 中使用事件发射器的最简单方法

egu*_*eys 2 javascript events ember.js

这是我当前对事件发射器的实现。

class Table {

  set onDiscard(cb) {
    this._onDiscard = cb;
  }

  notifyDiscard(s) {
    if (this._onDiscard) {
      this._onDiscard(s);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

在有多个事件的情况下,这会带来负担。

我可以使用什么库/功能/实现,以便我可以将其简化为一行。

Eri*_*ser 5

这是一个支持多个处理程序的简单方法:

class Table {
    on(type, cb) {
        this['_on' + type] = this['_on' + type] || [];
        this['_on' + type].push(cb);
    }

    emit(type, args) {
        this['_on' + type] && this['_on' + type].forEach((cb) => { cb(args) });
    }
}

var table = new Table();

table.on('started', function() { alert('started'); });
table.emit('started');
Run Code Online (Sandbox Code Playgroud)