2018-01-31 10:13:33 +00:00
|
|
|
module.exports = class Observable {
|
2018-02-13 10:42:44 +00:00
|
|
|
on(event, handler) {
|
|
|
|
this._addHandler('_handlers', event, handler);
|
2018-01-31 12:56:21 +00:00
|
|
|
}
|
2018-01-31 10:13:33 +00:00
|
|
|
|
2018-02-13 10:42:44 +00:00
|
|
|
once(event, handler) {
|
|
|
|
this._addHandler('_onceHandlers', event, handler);
|
2018-01-31 10:13:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async trigger(event, params) {
|
2018-02-13 10:42:44 +00:00
|
|
|
await this._triggerHandler('_handlers', event, params);
|
|
|
|
await this._triggerHandler('_onceHandlers', event, params);
|
|
|
|
if (this._onceHandlers && this._onceHandlers[event]) {
|
|
|
|
delete this._onceHandlers[event];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
_addHandler(name, event, handler) {
|
|
|
|
if (!this[name]) {
|
|
|
|
this[name] = {};
|
|
|
|
}
|
|
|
|
if (!this[name][event]) {
|
|
|
|
this[name][event] = [];
|
|
|
|
}
|
|
|
|
this[name][event].push(handler);
|
|
|
|
}
|
|
|
|
|
|
|
|
async _triggerHandler(name, event, params) {
|
|
|
|
if (this[name] && this[name][event]) {
|
|
|
|
for (let handler of this[name][event]) {
|
2018-01-31 10:13:33 +00:00
|
|
|
await handler(params);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-02-13 10:42:44 +00:00
|
|
|
}
|