Skip to content

Instantly share code, notes, and snippets.

@enijar
Last active November 1, 2016 03:30
Show Gist options
  • Save enijar/c860dfda7b95a0df92f8929305d6d566 to your computer and use it in GitHub Desktop.
Save enijar/c860dfda7b95a0df92f8929305d6d566 to your computer and use it in GitHub Desktop.
JavaScript Event System
const Event = {
events: {},
on(event, func) {
if (!this.events.hasOwnProperty(event)) {
this.events[event] = [];
}
this.events[event].push(func);
},
fire(event, data) {
if (!this.events.hasOwnProperty(event)) {
return;
}
this.events[event].map(func => func(data));
},
off(event) {
if (!this.events.hasOwnProperty(event)) {
return;
}
this.events[event].splice(0, this.events[event].length - 1);
if (this.events[event].length === 0) {
delete this.events[event];
}
}
};
export default Event;
@enijar
Copy link
Author

enijar commented Aug 20, 2016

Usage:

// Listen for events
Event.on('something', (data) => console.log(data));

// Fire events
Event.fire('something', {someKey: 'some value'});

// Remove events
Event.off('something');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment