Created
April 12, 2019 14:22
-
-
Save schmidtsonian/8a023034a2f5600b455afd2e2aed7019 to your computer and use it in GitHub Desktop.
A super-basic Javascript (publish subscribe) pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A super-basic Javascript (publish subscribe) pattern | |
* https://www.youtube.com/watch?v=nQRXi1SVOow | |
* https://gist.github.com/learncodeacademy/777349747d8382bfb722 | |
* | |
* @export | |
* @class Events | |
*/ | |
export default class Events { | |
/** | |
* Creates an instance of Events. | |
* | |
* @memberOf Events | |
*/ | |
constructor() { | |
if (!Events.instance) { | |
Events.instance = this; | |
} | |
this.events = {}; | |
return Events.instance; | |
} | |
/** | |
* Events bindings | |
* | |
* @param {string} eventName - event Name | |
* @param {Function} fn - | |
* | |
* @memberOf Events | |
*/ | |
on(eventName, fn) { | |
this.events[eventName] = this.events[eventName] || []; | |
this.events[eventName].push(fn); | |
} | |
/** | |
* Unbind event | |
* | |
* @param {string} eventName - event Name | |
* @param {Function} fn - | |
* | |
* @memberOf Events | |
*/ | |
off(eventName, fn) { | |
const {events} = this; | |
if (events[eventName]) { | |
for (let i = 0; i < events[eventName].length; i++) { | |
if (events[eventName][i] === fn) { | |
this.events[eventName].splice(i, 1); | |
break; | |
} | |
} | |
} | |
} | |
/** | |
* Trigger a specific event | |
* | |
* @param {string} eventName - event Name | |
* @param {...*} [params] - | |
* | |
* @memberOf Events | |
*/ | |
trigger(eventName, ...params) { | |
const {events} = this; | |
if (events[eventName]) { | |
events[eventName].forEach((fn) => { | |
fn(...params); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment