2018-01-31 10:13:33 +00:00
|
|
|
module.exports = class Observable {
|
2018-02-13 11:54:57 +00:00
|
|
|
on(event, listener) {
|
|
|
|
this._addListener('_listeners', event, listener);
|
2018-01-31 12:56:21 +00:00
|
|
|
}
|
2018-01-31 10:13:33 +00:00
|
|
|
|
2018-02-13 11:54:57 +00:00
|
|
|
once(event, listener) {
|
|
|
|
this._addListener('_onceListeners', event, listener);
|
2018-01-31 10:13:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async trigger(event, params) {
|
2018-02-13 11:54:57 +00:00
|
|
|
await this._triggerEvent('_listeners', event, params);
|
|
|
|
await this._triggerEvent('_onceListeners', event, params);
|
|
|
|
|
|
|
|
// clear once-listeners
|
|
|
|
if (this._onceListeners && this._onceListeners[event]) {
|
|
|
|
delete this._onceListeners[event];
|
2018-02-13 10:42:44 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-13 11:54:57 +00:00
|
|
|
_addListener(name, event, listener) {
|
2018-02-13 10:42:44 +00:00
|
|
|
if (!this[name]) {
|
|
|
|
this[name] = {};
|
|
|
|
}
|
|
|
|
if (!this[name][event]) {
|
|
|
|
this[name][event] = [];
|
|
|
|
}
|
2018-02-13 11:54:57 +00:00
|
|
|
this[name][event].push(listener);
|
2018-02-13 10:42:44 +00:00
|
|
|
}
|
|
|
|
|
2018-02-13 11:54:57 +00:00
|
|
|
async _triggerEvent(name, event, params) {
|
2018-02-13 10:42:44 +00:00
|
|
|
if (this[name] && this[name][event]) {
|
2018-02-13 11:54:57 +00:00
|
|
|
for (let listener of this[name][event]) {
|
|
|
|
await listener(params);
|
2018-01-31 10:13:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-02-13 11:54:57 +00:00
|
|
|
|
|
|
|
clearListeners() {
|
|
|
|
this._listeners = {};
|
|
|
|
this._onceListeners = {};
|
|
|
|
}
|
2018-02-13 10:42:44 +00:00
|
|
|
}
|