2
0
mirror of https://github.com/frappe/books.git synced 2024-12-23 11:29:03 +00:00
books/utils/observable.js

43 lines
1.1 KiB
JavaScript
Raw Normal View History

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 11:54:57 +00:00
_addListener(name, event, listener) {
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 11:54:57 +00:00
async _triggerEvent(name, event, params) {
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 = {};
}
}