Client: Implement event system (#4)
This commit is contained in:
parent
36ba716ad8
commit
ceca822f97
4 changed files with 81 additions and 7 deletions
42
public_html/js/events.js
Normal file
42
public_html/js/events.js
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue