Skip to content

Instantly share code, notes, and snippets.

@jorendorff
Last active August 31, 2017 17:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorendorff/5245857 to your computer and use it in GitHub Desktop.
Save jorendorff/5245857 to your computer and use it in GitHub Desktop.
//some deterministic event system, could be global or created with constructor
var events = new DeterministicEventSystem();
(function(){
//This object only exists inside this IIFE, not outside it
var myObject = {
handler: function(event){
console.log("handle event: " + event);
}
};
//add a listener to events temporarily, for one block of code
events.withListener("someEvent", myObject.handler, () => {
//the following causes the handler above to be called, resulting in output on the console
events.dispatchEvent("someEvent", {params:"someParams"});
});
})();
//myObject is not registered as a listener anymore
//the following does not output anything on the console
events.dispatchEvent("someEvent", {params:"someParams"});
//some weak event system, could be global or created with constructor
var events = new WeakEventSystem();
(function(){
//This object only exists inside this IIFE, not outside it
var myObject = {
handler: function(event){
console.log("handle event: " + event);
}
};
//add a listener to events, but events only has a weak reference to it
events.addEventListener("someEvent", myObject.handler);
//the following causes the handler above to be called, resulting in output on the console
events.dispatchEvent("someEvent", {params:"someParams"});
})();
//myObject does not exist anymore
//the following does not output anything on the console
events.dispatchEvent("someEvent", {params:"someParams"});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment