Publish/Subscribe (PUB/SUB) is a message pattern with two participants: Publisher and Subscriber. The publisher posts a message to a channel that the subscriber binds to, and when a message is posted to the channel, the Subscriber receives the notification. Publishers and Subscribers are fully decoupled, sharing only one channel name with each other.
This mode improves the serviceability of the application and makes the application easy to extend.
Simple design idea: The design Channel records the published information, and then executes the successful callback function (listening for events from the channel) in the Subscriber.
var PubSub = { function(key, callback) {
This._callbacks = This._callbacks | | {};
This._callbacks[key] = This._callbacks[key] | | [];
This._callbacks[key].push (callback);
This._callbacks | | (this.callbacks = {}); ( this . _callbacks[key] | | (this . _callbacks[key] = []). push (callback); return this ; }, publish: function () { var arg = Array.prototype.slice.call (arguments, 0 var key = Args.shift ();//Find key var list, calls, I, l;
//No _callbacks direct return, no _callbacks[key] Direct return
if (this._callbacks && This._callbacks[key]) {
List = This._callbacks[key]
calls = This._callbacks;
}else{
return this;
//}
if(! (calls = This. _callbacks))return This; if(! (List = This. _callbacks[key]))return This;
Execute callback for(i = 0; l = list.length; i < L; i++) {list[i].apply ( This, args); } return This; }};//How to usePubsub.subscribe ("Leju",function() {alert ("Leju"); }); Pubsub.publish ("Leju");
Above the native JS implementation, the following time jquery is implemented.
$ (function() { var obj = $ ({}); function () { obj.bind.apply (obj, arguments); } function () { obj.unbind.apply (obj, arguments); } function () { obj.trigger.apply (obj, arguments); }
Calling method function
Console.log (Event.type, a); }); " Leju "," Leju "); })
Easy Publish/Subscribe mode for JavaScript