Created
May 10, 2014 06:26
-
-
Save bingeboy/aa132221655258699fd0 to your computer and use it in GitHub Desktop.
pubsub prototype pattern js
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() {}; | |
//this will store the callback into the topics array | |
PubSub.prototype.subscribe = function( topic, callback, context) { | |
context = context || this; | |
this._topics = this._topics || {}; | |
this._topics[topic] = this._topics.topic || []; | |
this._topics[topic].push({ "content", context, "callback", callback }); | |
} | |
//takes the topic's call back and calls with with the proper context | |
PubSub.prototype.publish = function( topic ){ | |
context = context || this; | |
this._topics[topic].forEach(function(subscription) { | |
subscription.callback.callback(subscription.context); | |
} | |
} | |
//topics | |
var Tags = function(){}; | |
Tags.prototype.listTags = function() { | |
this._tags = this._tags || [ ]; | |
return this._tags; | |
} | |
Tags.prototype.addTag = function(tag){ | |
this._tags = this._tags || [ ]; | |
this._tags.push(tag); | |
this.publish && this.publish("Tag Added"); | |
} | |
Tags.prototype.removeTag = function(){ | |
this._tags = this._tags || [ ]; | |
var index = this._tags.indexOf(tag); | |
this._tags = this._tags.splice(index, 1); | |
} | |
Tags.prototype.countTags = function(){ | |
return this._tags.length; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment