这是我当前的事件发射器实现。
class Table {
set onDiscard(cb) {
this._onDiscard = cb;
}
notifyDiscard(s) {
if (this._onDiscard) {
this._onDiscard(s);
}
}
}
在有多个事件的情况下,这会带来负担。
我可以使用什么库/功能/实现,以便将其简化为一行。
最佳答案
这是一个支持多个处理程序的简单方法:
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');
关于javascript - 在 ES6 中使用事件发射器的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30003865/