html 订阅发布,发布-订阅模式.html
var pubsub = {};
(function(myObject) {
// Storage for topics that can be broadcast 可以廣播的主題的存儲(chǔ)
// or listened to 或者聽(tīng)
var topics = {};
// A topic identifier 主題標(biāo)識(shí)符
var subUid = -1;
// Publish or broadcast events of interest 發(fā)布或廣播感興趣的事件
// with a specific topic name and arguments 具有特定的主題名稱和參數(shù)
// such as the data to pass along 如數(shù)據(jù)傳遞
myObject.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;
};
// Subscribe to events of interest 訂閱感興趣的事件
// with a specific topic name and a 具有特定的主題名稱和
// callback function, to be executed 回調(diào)函數(shù),將被執(zhí)行
// when the topic/event is observed 當(dāng)觀察到主題/事件時(shí)
myObject.subscribe = function( topic, func ) {
if (!topics[topic]) {
topics[topic] = [];
}
var token = ( ++subUid ).toString();
topics[topic].push({
token: token,
func: func
});
return token;
};
// Unsubscribe from a specific 取消訂閱
// topic, based on a tokenized reference 主題,基于標(biāo)記化參考
// to the subscription 訂閱
myObject.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 ));
// A simple message logger that logs any topics and data received through our 一個(gè)簡(jiǎn)單的消息記錄器,記錄通過(guò)我們接收的任何主題和數(shù)據(jù)。
// subscriber 用戶
var messageLogger = function ( topics, data ) {
console.log( "Logging: " + topics + ": " + data );
};
// Subscribers listen for topics they have subscribed to and 訂閱者監(jiān)聽(tīng)他們訂閱的主題和
// invoke a callback function (e.g messageLogger) once a new 調(diào)用一個(gè)新的回調(diào)函數(shù)(例如MasigelgGER)
// notification is broadcast on that topic 這個(gè)主題廣播通知
var subscription = pubsub.subscribe( "inbox/newMessage", messageLogger );
// Publishers are in charge of publishing topics or notifications of 出版商負(fù)責(zé)出版主題或通知。
// interest to the application. e.g: 對(duì)應(yīng)用程序有興趣。例如:
pubsub.publish( "inbox/newMessage", "hello world!" );
// or
pubsub.publish( "inbox/newMessage", ["test", "a", "b", "c"] );
// or
pubsub.publish( "inbox/newMessage", {
sender: "hello@google.com",
body: "Hey again!"
});
// We can also unsubscribe if we no longer wish for our subscribers 如果我們不再希望我們的訂戶,我們也可以退訂。
// to be notified 被通知
pubsub.unsubscribe( subscription );
// Once unsubscribed, this for example won't result in our 一旦退訂,這將不會(huì)導(dǎo)致我們的
// messageLogger being executed as the subscriber is MasaGelgGER作為訂閱服務(wù)器執(zhí)行
// no longer listening 不再聽(tīng)
pubsub.publish( "inbox/newMessage", "Hello! are you still there?" );
一鍵復(fù)制
編輯
Web IDE
原始數(shù)據(jù)
按行查看
歷史
總結(jié)
以上是生活随笔為你收集整理的html 订阅发布,发布-订阅模式.html的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 计算机会计的专业知识竞赛,会计知识大赛主
- 下一篇: wifi 频段表_史上最全无线通信频率分