Last active
August 29, 2015 14:14
-
-
Save laispace/5e93e499c58bc54d8b24 to your computer and use it in GitHub Desktop.
设计模式-发布订阅模式
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
// pattern-pubsub.js | |
var pubsub = {}; | |
(function (ps) { | |
var topics = {}; // store topics | |
var subId = -1; // identify subcribers | |
ps.publish = function (topic, args) { | |
var subcribers = topics[topic]; | |
// no subscribes subcribing the topic | |
if (!subcribers) { | |
return false; | |
} | |
for (var i = 0; i < subcribers.length; i++) { | |
// notify every subscriber with arguments | |
subcribers[i].func(args); | |
} | |
return this; | |
}; | |
ps.subscribe = function (topic, func) { | |
var subcribers = topics[topic]; | |
// first subscriber! | |
if (!subcribers) { | |
// init subscribers list | |
topics[topic] = []; | |
} | |
// generate unique id | |
var id = ++subId; | |
// add this subscriber into the list | |
topics[topic].push({ | |
id: id, | |
func: func | |
}); | |
return id; | |
}; | |
ps.unsubscribe = function (id) { | |
for(var t in topics) { | |
var subcribers = topics[t]; | |
for (var i = 0; i < subcribers.length; i++) { | |
// find the topic with id | |
if (subcribers[i].id === id) { | |
// delete id | |
subcribers.splice(i, 1); | |
// find the topic with id, return the id | |
return id; | |
} | |
}; | |
} | |
// do not find the topic with id, just return this | |
return this; | |
}; | |
})(pubsub); | |
// subscribe a topic name 'topic1' | |
var id1 = pubsub.subscribe('topic1', function (args) { | |
console.log('topic1', args); | |
}); | |
// subscribe a topic name 'topic2' | |
var id2 = pubsub.subscribe('topic2', function (args) { | |
console.log('topic2', args); | |
}); | |
// pubsub the topic 'topic1' | |
pubsub.publish('topic1', 'hello xiaolai!'); | |
// pubsub the topic 'topic1' | |
pubsub.publish('topic2', 'hello 赖小赖!'); | |
// now we unsubscribe the 'topic1' | |
pubsub.unsubscribe(id1); | |
// pubsub the topic 'topic1' and 'topic2' again | |
pubsub.publish('topic1', 'hello xiaolai again!'); | |
pubsub.publish('topic1', 'hello xiaolai again!'); |
发布订阅模式的优点是,可以让多个模块之间解耦,通过事件的形式执行特定的操作,无需关心其他模块的信息
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
几个优秀的发布订阅库:
http://radio.uxder.com/
https://github.com/mroderick/PubSubJS
https://github.com/phiggins42/bloody-jquery-plugins/blob/55e41df9bf08f42378bb08b93efcb28555b61aeb/pubsub.js
http://amplifyjs.com
https://gist.github.com/826794