Skip to content

Instantly share code, notes, and snippets.

@Frenchcooc
Created December 2, 2018 18:31
Show Gist options
  • Save Frenchcooc/044fbdbe0b0b9155ef90a318992f12d7 to your computer and use it in GitHub Desktop.
Save Frenchcooc/044fbdbe0b0b9155ef90a318992f12d7 to your computer and use it in GitHub Desktop.
Easy to use JS EventListener class
"use strict";
class EventListener {
constructor () {
// Declare variables
this._onEvents = [];
return this;
};
on (eventName, callback) {
if (!eventName || !callback) { return; }
else if (typeof eventName !== "string") { return ;}
else if (typeof callback !== "function") { return; }
this._onEvents.push({
"name": eventName,
"callback": callback
});
};
onEvent (eventName) {
console.log("New event:", eventName);
const events = this._onEvents;
for (var i = 0; i < events.length; i++) {
let event = events[i];
if (event.name == eventName) {
event['callback']();
}
}
}
};
module.exports = EventListener;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment