Last active
December 21, 2015 18:39
-
-
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.
This file contains 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
/** | |
* 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