Created
December 2, 2018 18:31
-
-
Save Frenchcooc/044fbdbe0b0b9155ef90a318992f12d7 to your computer and use it in GitHub Desktop.
Easy to use JS EventListener class
This file contains 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
"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