Skip to content

Instantly share code, notes, and snippets.

@hughfdjackson
Last active December 12, 2015 02:29
Show Gist options
  • Save hughfdjackson/4699331 to your computer and use it in GitHub Desktop.
Save hughfdjackson/4699331 to your computer and use it in GitHub Desktop.
var extend = function(t, f){ for ( var p in f ) t[p] = f[p]; return t }
// a Pub/Sub mixin
var Hub = {
sub: function(name, cb){
if ( ! this.channels ) this.channels = {}
if ( ! this.channels[name]) this.channels[name] = []
this.channels[name].push(cb)
return this
},
pub: function(name, msg){
if ( ! this.channels || ! this.channels[name] ) return this
this.channels[name].forEach(function(cb){ cb(msg) })
return this
}
}
// mix in Hub to some object, just because we can. that obj may have lots of other logic
var myHub = extend({}, Hub)
// our callback is just a sub to our pub
myHub.sub('my event', function(msg){ console.log('first subscriber to:', msg) })
myHub.sub('my event', function(msg){ console.log('second subscriber to:', msg) })
myHub.pub('my event', 'hi there')
var myHub2 = extend({}, Hub)
myHub2.pub('my event', 'wait, no one is listening')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment