Last active
September 17, 2016 17:39
-
-
Save darcyclarke/a49526f050b734a23cbadf3258c6313c to your computer and use it in GitHub Desktop.
Library agnostic publish/subscribe
This file contains hidden or 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
| /*! | |
| * | |
| * Library Agnostic Pubsub | |
| * http://darcyclarke.me/articles/development/library-agnostic-pubsub-publish-subscribe/ | |
| * | |
| * Copyright 2016, Darcy Clarke | |
| * Do what you want license... | |
| * | |
| */ | |
| (function(window){ | |
| var ps = window.ps = {}; | |
| ps.subscriptions = []; | |
| ps.subscribe = function(name, callback){ | |
| ps.subscriptions.push({"name": name, "callback": callback}); | |
| return [name,callback]; | |
| }; | |
| ps.unsubscribe = function(args){ | |
| for(x=0;x<ps.subscriptions.length;x++){ | |
| if(ps.subscriptions[x].name == args[0], ps.subscriptions[x].callback == args[1]) | |
| ps.subscriptions.splice(x, 1); | |
| } | |
| }; | |
| ps.publish = function(name, args){ | |
| var temp = []; | |
| if(ps.subscriptions.length > 0){ | |
| for(var x=0;x<ps.subscriptions.length;x++) { | |
| if(ps.subscriptions[x].name == name) | |
| temp.push({"fn":ps.subscriptions[x].callback}); | |
| } | |
| for(x=0;x<temp.length;x++){ | |
| temp[x].fn.apply(this,[args]); | |
| } | |
| } | |
| }; | |
| })(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment