Skip to content

Instantly share code, notes, and snippets.

@cngondo
Last active February 12, 2020 23:40
Show Gist options
  • Save cngondo/386dd7a71526cfcf1f392bcb9462d6f4 to your computer and use it in GitHub Desktop.
Save cngondo/386dd7a71526cfcf1f392bcb9462d6f4 to your computer and use it in GitHub Desktop.
var addEventSystem = function(target){
// Stores all the events. Keys -> event names, Values -> array of
// all callbacks for the events
target.reactionsTo = {};
target.on = function(event, callback){
// the event will act as the keys to the system
this.reactionsTo[event] = this.reactionsTo[event] || []
this.reactionsTo[event].push(callback);
}
// Trigger all the callbacks based on the event being passed
target.trigger = function(event){
_.each(this.reactionsTo[event], function(callback){
callback();
})
}
}
// Example
var mouth = {
eat: function(){}
};
addEventSystem(mouth);
var stomach = {
digest: function(){}
};
addEventSystem(stomach);
stomach.on('hungry', mouth.eat);
stomach.on('hungry', stomach.digest);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment