Skip to content

Instantly share code, notes, and snippets.

@laispace
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laispace/5e93e499c58bc54d8b24 to your computer and use it in GitHub Desktop.
Save laispace/5e93e499c58bc54d8b24 to your computer and use it in GitHub Desktop.
设计模式-发布订阅模式
// 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!');
@laispace
Copy link
Author

laispace commented Feb 7, 2015

发布订阅模式的优点是,可以让多个模块之间解耦,通过事件的形式执行特定的操作,无需关心其他模块的信息

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment