Created
August 12, 2014 08:30
-
-
Save rikan/941ca0a86824c2cf788d to your computer and use it in GitHub Desktop.
$.Callbacks实现订阅模式
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
| (function(){ | |
| var topics = {}; | |
| jQuery.Topic = function(id){ | |
| var callback = $.Callbacks(); | |
| var topic = id && topics[id]; | |
| if(!topic){ | |
| topic = { | |
| publish: callback.fire, | |
| subscribe: callback.add, | |
| unsubscribe: callback.remove | |
| }; | |
| topic.subscribe(function(){console.log("---" + id + "---")}); | |
| } | |
| if(id){ | |
| topics[id] = topic; | |
| } | |
| return topic; | |
| } | |
| var fn1 = function(param){ | |
| console.log("fn1 says:" + param); | |
| } | |
| var fn2 = function(param){ | |
| console.log("fn2 says:" + param); | |
| } | |
| var dfd = $.Deferred(); | |
| jQuery.Topic("topic1").subscribe(fn1); | |
| jQuery.Topic("topic1").subscribe(fn2); | |
| jQuery.Topic("topic2").subscribe(fn1); | |
| dfd.done(jQuery.Topic("topic1").publish); | |
| console.log("waiting"); | |
| dfd.resolve("resolved!"); | |
| }).call(this) |
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
| (function(){ | |
| var topics = {}; | |
| jQuery.Topic = function(id){ | |
| var callback = $.Callbacks(); | |
| var topic = id && topics[id]; | |
| if(!topic){ | |
| topic = { | |
| publish: callback.fire, | |
| subscribe: callback.add, | |
| unsubscribe: callback.remove | |
| }; | |
| topic.subscribe(function(){console.log("---" + id + "---")}); | |
| } | |
| if(id){ | |
| topics[id] = topic; | |
| } | |
| return topic; | |
| } | |
| var fn1 = function(param){ | |
| console.log("fn1 says:" + param); | |
| } | |
| var fn2 = function(param){ | |
| console.log("fn2 says:" + param); | |
| } | |
| jQuery.Topic("topic1").subscribe(fn1); | |
| jQuery.Topic("topic1").subscribe(fn2); | |
| jQuery.Topic("topic2").subscribe(fn1); | |
| jQuery.Topic("topic1").publish("msg_1"); | |
| jQuery.Topic("topic2").publish("msg_2"); | |
| jQuery.Topic("topic2").publish("msg_3"); | |
| }).call(this) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment