看看这个:
(基于http://web.archive.org/web/20130120010146/http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/处的存档版本从过期的博客页面http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/重印)
Publish / Subscribe With jQuery
June 17th, 2008
为了编写与Google Gears的离线功能集成的jQuery UI,我一直在使用一些代码来使用jQuery轮询网络连接状态.
网络检测对象
基本前提非常简单.我们创建一个网络检测对象的实例,它将定期轮询URL.如果这些HTTP请求失败,我们可以假设网络连接已丢失,或者服务器在当前时间根本无法访问.
$.networkDetection = function(url,interval){
var url = url;
var interval = interval;
online = false;
this.StartPolling = function(){
this.StopPolling();
this.timer = setInterval(poll, interval);
};
this.StopPolling = function(){
clearInterval(this.timer);
};
this.setPollInterval= function(i) {
interval = i;
};
this.getOnlineStatus = function(){
return online;
};
function poll() {
$.ajax({
type: "POST",
url: url,
dataType: "text",
error: function(){
online = false;
$(document).trigger('status.networkDetection',[false]);
},
success: function(){
online = true;
$(document).trigger('status.networkDetection',[true]);
}
});
};
};
您可以在此处查看演示.将您的浏览器设置为脱机工作,然后查看…会发生什么情况.不,这不是很令人兴奋.
触发和绑定
不过,令人兴奋的(或者至少是让我兴奋的)是通过应用程序传递状态的方法.我偶然发现了一种使用jQuery的触发器和绑定方法实现发布/订阅系统的方法,这种方法在很大程度上没有讨论.
演示代码比它需要的更迟钝.网络检测对象将"状态"事件发布到文档中,文档将主动侦听这些事件,然后将"通知"事件发布到所有订阅者(稍后将详细介绍这些订阅者).这背后的原因是,在现实世界的应用程序中,可能会有更多的逻辑控制"通知"事件的发布时间和方式.
$(document).bind("status.networkDetection", function(e, status){
// subscribers can be namespaced with multiple classes
subscribers = $('.subscriber.networkDetection');
// publish notify.networkDetection even to subscribers
subscribers.trigger("notify.networkDetection", [status])
/*
other logic based on network connectivity could go here
use google gears offline storage etc
maybe trigger some other events
*/
});
由于jQuery的以DOM为中心的方法,事件被发布到DOM元素(在其上触发).这可以是一般事件的窗口或文档对象,也可以使用 Select 器生成jQuery对象.我在演示中采用的方法是创建一种几乎是命名空间的方法来定义订阅者.
将成为订阅者的DOM元素简单地分为"订阅者"和"网络检测".然后,我们可以通过在100上触发notify事件,将事件仅发布到这些元素(在演示中只有一个元素)
作为.subscriber.networkDetection
个订阅者组的一部分的100 div则具有绑定到它的匿名函数,从而有效地充当侦听器.
$('#notifier').bind("notify.networkDetection",function(e, online){
// the following simply demonstrates
notifier = $(this);
if(online){
if (!notifier.hasClass("online")){
$(this)
.addClass("online")
.removeClass("offline")
.text("ONLINE");
}
}else{
if (!notifier.hasClass("offline")){
$(this)
.addClass("offline")
.removeClass("online")
.text("OFFLINE");
}
};
});
所以,这就对了.这一切都相当冗长,而且我的示例一点也不令人兴奋.它也没有展示使用这些方法可以做的任何有趣的事情,但是如果有人通过源代码对挖洞感兴趣,请随意.所有代码都内联在演示页面的头部