Client: Implement event system (#4)

This commit is contained in:
Lexi / Zoe 2019-01-20 21:12:41 +01:00
parent 36ba716ad8
commit ceca822f97
Signed by: binaryDiv
GPG key ID: F8D4956E224DA232
4 changed files with 81 additions and 7 deletions

42
public_html/js/events.js Normal file
View file

@ -0,0 +1,42 @@
"use strict";
/**
* Base class to implement an event system in any class. Events can be dispatched and
* subscribed/unsubscribed. Events can have multiple registered callbacks.
*/
class EventDispatcher {
constructor() {
this._events = {};
}
/**
* Dispatch a named event. Calls all callbacks that are subscribed to this event.
*/
dispatch(eventName, data = null) {
if (this._events[eventName]) {
this._events[eventName].forEach((callback) => {
callback(data);
});
}
}
/**
* Subscribe to an event.
*/
on(eventName, callback) {
if (!this._events[eventName]) {
this._events[eventName] = [];
}
this._events[eventName].push(callback);
}
/**
* Unsubscribe from an event. Not sure how to unsubscribe anonymous functions though.
* If callback is not found, nothing happens.
*/
off(eventName, callback) {
if (this._events[eventName]) {
this._events[eventName] = this._events[eventName].filter(item => item !== callback);
}
}
}