Created
October 25, 2012 22:50
-
-
Save mnishihan/3955963 to your computer and use it in GitHub Desktop.
JavaScript: Library Agnostic Pub/Sub
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
App = {}; | |
App.cache = {}; | |
App.publish = function(topic, args){ | |
App.cache[topic] && $.each(App.cache[topic], function(){ | |
this.apply($, args || []); | |
}); | |
}; | |
App.subscribe = function(topic, callback){ | |
if(!App.cache[topic]){ | |
App.cache[topic] = []; | |
} | |
App.cache[topic].push(callback); | |
return [topic, callback]; | |
}; | |
App.unsubscribe = function(handle){ | |
var t = handle[0]; | |
App.cache[t] && $.each(App.cache[t], function(idx){ | |
if(this == handle[1]){ | |
App.cache[t].splice(idx, 1); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment