Last active
February 12, 2020 23:40
-
-
Save cngondo/386dd7a71526cfcf1f392bcb9462d6f4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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