手写一个观察者,发布订阅模式
wengjq opened this issue · comments
var pubsub = {};
(function(q) {
var topics = {},
subUid = -1;
// 使用特定主题名称和参数(如要传递的数据)发布事件
q.publish = function(topic, args) {
if (!topics[topic]) {
return false;
}
var subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func( topic, args );
}
return this;
};
// 当观察到话题/事件时,用特定的话题名称和回调函数来订阅事件
q.subscribe = function(topic, func) {
if (!topics[topic]) {
topics[topic] = [];
}
var token = ( ++subUid ).toString();
topics[topic].push({
token: token,
func: func
});
return token;
};
// 根据对订阅的标记化引用,取消订阅特定主题
q.unsubscribe = function(token) {
for (var m in topics) {
if (topics[m]) {
for (var i = 0, j = topics[m].length; i < j; i++) {
if (topics[m][i].token === token) {
topics[m].splice( i, 1 );
return token;
}
}
}
}
return this;
};
}(pubsub));
文不对题