JavaScript event mediator / communication middle-man
Many planes, one control tower - all the planes talk to the tower, the tower talks to all the planes... safe landings.
Demo page: http://jaredshaunsmith.github.io/intercom/example.html
To install via npm:
npm install intercom --save-dev
// ///////////////////////////////////////////////////////////////////////////// Intercom - JavaScript mediator// Jared Smith - 2014// Based on the previous work of Ryan Florence (https://github.com/rpflorence)// ///////////////////////////////////////////////////////////////////////////varIntercom=(function(){varlisten=function(channel,fn){if(!Intercom.channels[channel])Intercom.channels[channel]=[];Intercom.channels[channel].push({context: this,callback: fn});returnthis;},disconnect=function(channel){if(!Intercom.channels[channel])returnfalse;deleteIntercom.channels[channel];returnthis;},broadcast=function(channel){if(!Intercom.channels[channel])returnfalse;varargs=Array.prototype.slice.call(arguments,1);for(vari=0,l=Intercom.channels[channel].length;i<l;i++){vartuneIn=Intercom.channels[channel][i];if(typeoftuneIn.callback=='function'){tuneIn.callback.apply(tuneIn.context,args);}else{tuneIn.context[tuneIn.callback].apply(tuneIn.context,args);}}returnthis;};return{channels: {},listen: listen,disconnect: disconnect,broadcast: broadcast,installOn: function(obj){obj.listen=listen;obj.disconnect=disconnect;obj.broadcast=broadcast;}};})();// create an objectvarobj={'foo' : 'bar'};// install Intercom on the objIntercom.installOn(obj);// bind listening to our event on the objobj.listen('someEvent',function(arg){alert(arg);});// then to triggerobj.broadcast('someEvent','woooooot tooooot');// create an object with a methodvarobj={'foo' : function(arg){this.bar=arg;}};// install Intercom on the objobj.installOn(obj);// bind listening and pass string instead of function// string will be automatically detected and called on the contextobj.listen('bigEvent','foo');// the to triggerobj.broadcast('bigEvent','hello world');// check resultsconsole.log(obj.bar)// "hello world";