Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
简化版的 js 订阅者模式实现代码,简化了 [PubSub](https://github.com/mroderick/PubSubJS)
var PubSub = (function() {
var messages = {},
lastUid = -1;
function hasKeys(obj) {
for (var key in obj){
return true;
}
return false;
}
return {
/**
* Publishes the message, passing the data to it's subscribers
* @param { String } message The message to publish
* @param {} data The data to pass to subscribers
* */
publish: function(message, data) {
if (!message) return false;
var topic = message ? message.toString() : '';
var hasSubscribers = messages.hasOwnProperty( topic ) && hasKeys(messages[topic]);
if (!hasSubscribers) {
return false;
}
var subscribers = messages[topic];
for (var i in subscribers) {
setTimeout( subscribers[i](data), 0 );
}
},
/**
* Subscribes the passed function to the passed message. Every returned token is unique and should be stored if you need to unsubscribe
* @function
* @param { String } message The message to subscribe to
* @param { Function } func The function to call when a new message is published
* @return { String }
*/
subscribe: function(message, func) {
if (!message) return false;
var topic = message ? message.toString() : '';
if ( typeof func !== 'function'){
return false;
}
// topic is not registered yet
if ( !messages.hasOwnProperty( topic ) ){
messages[topic] = {};
}
var token = 'uid_' + String(++lastUid);
messages[topic][token] = func;
// return token for unsubscribing
return token;
},
/**
* Removes subscriptions
*
* - When passed a token, removes a specific subscription.
*
* - When passed a topic, removes all subscriptions for that topic (hierarchy)
* @function
* @public
* @param { String } value A token or topic to unsubscribe from
* @example // Unsubscribing with a token
* var token = PubSub.subscribe('mytopic', myFunc);
* PubSub.unsubscribe(token);
* @example // Unsubscribing from a topic
* PubSub.unsubscribe('mytopic');
*/
unsubscribe: function(value){
var isTopic = messages.hasOwnProperty(value);
if (isTopic) {
delete messages[value];
} else { // is Token
for (var m in messages){
if (messages[m].hasOwnProperty(value)){
delete messages[m][value];
// tokens are unique, so we can just stop here
break;
}
}
}
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.