2
0
mirror of https://github.com/frappe/books.git synced 2024-11-10 07:40:55 +00:00
books/utils/observable.js

36 lines
963 B
JavaScript
Raw Normal View History

2018-01-31 10:13:33 +00:00
module.exports = class Observable {
on(event, handler) {
this._addHandler('_handlers', event, handler);
2018-01-31 12:56:21 +00:00
}
2018-01-31 10:13:33 +00:00
once(event, handler) {
this._addHandler('_onceHandlers', event, handler);
2018-01-31 10:13:33 +00:00
}
async trigger(event, params) {
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);
}
}
}
}