게시 구독 메커니즘

2866 단어 서버 스크립트

인스턴스 게시 / 구독


1. 발표
var pubsub = {};
(function(q) {
var topics = {},
subUid = -1;

// Publish or broadcast events of interest
// with a specific topic name and arguments
// such as the data to pass along
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;
};

2. 구독
// Subscribe to events of interest
// with a specific topic name and a
// callback function, to be executed
// when the topic/event is observed
q.subscribe = function( topic, func ) {
if (!topics[topic]) {
topics[topic] = [];
}

var token = ( ++subUid ).toString();
topics[topic].push({
token: token,
func: func
});

return token;
};

3. 구독 취소

// Unsubscribe from a specific
// topic, based on a tokenized reference
// to the subscription
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 ));

좋은 웹페이지 즐겨찾기