Last active
September 15, 2015 13:00
-
-
Save Kasahs/e14811d0a557e226f2fb to your computer and use it in GitHub Desktop.
simple javascript pubsub example
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
var PubSub = (function(){ | |
var mapping = {}; | |
return { | |
sub: function(eventName, callback, obj){ | |
callback = callback || _.noop; | |
if(!_.isFunction(callback)){ | |
console.error("callback is not a function"); | |
return; | |
} | |
if(mapping[obj.__guid__ + ":" + eventName]){ | |
mapping[obj.__guid__ + ":" + eventName].push(callback); | |
} else { | |
mapping[obj.__guid__ + ":" + eventName] = []; | |
mapping[obj.__guid__ + ":" + eventName].push(callback); | |
} | |
}, | |
pub: function(eventName, data){ | |
data = data || {}; | |
_.each(mapping[this.__guid__ + ":" + eventName], function(callback){ | |
callback(data); | |
}); | |
} | |
}; | |
})(_); | |
// demo usage | |
var BaseObj = function(){ | |
this.__guid__ = Lybrate.Utils.GUID(); | |
}; | |
_.extend(BaseObj.prototype, PubSub); | |
var Foo = function(msg){ | |
BaseObj.call(this); | |
console.log(this.__guid__); | |
this.msg = msg; | |
}; | |
Foo.prototype = Object.create(BaseObj.prototype); | |
_.extend(Foo.prototype, { | |
printMsg: function(){ | |
console.log(this.msg); | |
} | |
}); | |
var Boo = function(msg){ | |
BaseObj.call(this); | |
console.log(this.__guid__); | |
this.msg = msg; | |
}; | |
Boo.prototype = Object.create(BaseObj.prototype); | |
_.extend(Boo.prototype, { | |
printMessage: function(){ | |
console.log(this.msg); | |
} | |
}); | |
// test | |
$(document).ready(function(){ | |
var foo = new Foo("Hello world!"); | |
var boo = new Boo("Hi there!"); | |
var foo2 = new Foo("Foo2 here!"); | |
var boo2 = new Boo("Boo2 here!"); | |
foo.sub("change", function(data){ | |
console.log("foo heard change"); | |
console.log(data); | |
}, boo); | |
foo.sub("change", function(data){ | |
console.log("foo heard change"); | |
console.log(data); | |
}, boo2); | |
boo.sub("change", function(data){ | |
console.log("boo heard change"); | |
console.log(data); | |
}, foo); | |
boo.sub("change", function(data){ | |
console.log("boo heard change"); | |
console.log(data); | |
}, foo2); | |
foo2.sub("change", function(data){ | |
console.log("foo2 heard change"); | |
console.log(data); | |
}, boo2); | |
boo2.sub("change", function(data){ | |
console.log("boo2 heard change"); | |
console.log(data); | |
}, foo2); | |
window.setTimeout(function(){ | |
foo.pub("change", "foo changed"); | |
boo.pub("change", "boo changed"); | |
}, 2000); | |
window.setTimeout(function(){ | |
foo2.pub("change", "foo2 changed"); | |
boo2.pub("change", "boo2 changed"); | |
}, 4000); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment