Skip to content

Instantly share code, notes, and snippets.

@sir-ragna
Last active December 21, 2015 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sir-ragna/6348410 to your computer and use it in GitHub Desktop.
Save sir-ragna/6348410 to your computer and use it in GitHub Desktop.
Communication between wrapped code JS. Wrapping is nice if you want to use code from other projects, but sometimes that code has to communicate. So I wrote this to check if it would work the way I hoped.
/**
* Further reading:
* Namespaces in JS http://www.dustindiaz.com/namespace-your-javascript/
*/
var observable = (function(){
var observers = [];
return {
observe : function(o){
// start observing this observable object
// optional, verify 'o' has a function 'notify'
observers.push(o);
},
unobserve : function(o){
observers.splice(observers.index(o), 1);
},
fire_event : function(event_name){
var i = observers.length;
while (i--) {
observers[i].notify(event_name);
}
}
};
})();
var event_watcher = (function(){
// full of functions
var event_received = function(e){
console.log("Eventwatcher succesfully received event " + e);
}
return {
notify : function(e){
event_received(e);
}
};
})();
// let event_watcher observe the observable
observable.observe(event_watcher);
observable.fire_event('somethinghappened');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment