13
0
livetrax/share/web_surfaces/shared/base/observable.js

64 lines
1.8 KiB
JavaScript
Raw Normal View History

/*
* Copyright © 2020 Luciano Iam <lucianito@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
2020-06-14 06:10:30 -04:00
export default class Observable {
constructor () {
this._observers = {};
}
2020-06-14 06:18:21 -04:00
addObserver (event, observer) {
// event=undefined means the caller is interested in observing all events
if (!(event in this._observers)) {
this._observers[event] = [];
}
2020-06-14 06:18:21 -04:00
this._observers[event].push(observer);
}
2020-06-14 06:18:21 -04:00
removeObserver (event, observer) {
// event=undefined means the caller is not interested in any event anymore
if (typeof(event) == 'undefined') {
for (const event in this._observers) {
this.removeObserver(event, observer);
}
} else {
2020-06-14 06:18:21 -04:00
const index = this._observers[event].indexOf(observer);
if (index > -1) {
2020-06-14 06:18:21 -04:00
this._observers[event].splice(index, 1);
}
}
}
2020-06-14 06:18:21 -04:00
notifyObservers (event, ...args) {
// always notify observers that observe all events
if (undefined in this._observers) {
for (const observer of this._observers[undefined]) {
2020-06-14 06:18:21 -04:00
observer(event, ...args);
}
}
2020-06-14 06:18:21 -04:00
if (event in this._observers) {
for (const observer of this._observers[event]) {
observer(...args);
}
}
}
}