Skip to content

Instantly share code, notes, and snippets.

@OzanKurt
Forked from JustSteveKing/event.js
Created January 13, 2023 01:56
Show Gist options
  • Save OzanKurt/48656edfe789a7ae18d7ddedb2e207ae to your computer and use it in GitHub Desktop.
Save OzanKurt/48656edfe789a7ae18d7ddedb2e207ae to your computer and use it in GitHub Desktop.
Custom Event Handler
class Event {
constructor() {
this.events = {};
}
fire(event, data) {
const Event = this.events[event];
if( Event ) {
Event.forEach(callback => {
callback.call(null, data);
});
}
}
listen(event, callback) {
if(!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(callback);
return () => {
this.events[event] = this.events[event].filter(eventCallback => callback !== eventCallback);
}
}
list() {
return console.dir(this.events);
}
}
let E = new Event();
E.listen('event:test-event', data => {
console.log(data);
});
E.fire('event:test-event', {name: 'test'});
E.list();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment