JQuery中发布-订阅模式在网络可用性轮询中的实现
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JQuery中发布-订阅模式在网络可用性轮询中的实现相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <link rel="stylesheet" href="/css/main.css" type="text/css" media="all" /> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script> <script type="text/javascript"> // see article http://jamazon.co.uk/web/2008/06/17/publish-subscribe-with-jquery/ $.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]); } }); }; }; $(document).ready(function(){ network = new $.networkDetection("poll.php", 5000); network.StartPolling(); $(document).bind("status.networkDetection", function(e, status){ // subscribers can be namespaced with multiple classes subscribers = $('.subscriber.networkDetection'); // publish notify.networkDetection 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 */ }); /* Listen for notify.networkDetection events. This could equally be listening directly to status.networkDetection events */ $('#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"); } }; }); }); </script> <style type="text/css"> * { font-family:verdana, arial, helvetica, sans-serif; font-weight:bold; } #notifier{ margin:auto; margin-top:200px; border:1px solid #ccc; color:#333; width:300px; padding:20px; text-align:center; } #notifier.online{ color:#fff; background:#3c3; border-color:#3c3; } #notifier.offline{ color:#fff; background:#f66; border-color:#f66; } </style> </head> <body> <ul id="listItems"> </ul> </body> </html>
以上是关于JQuery中发布-订阅模式在网络可用性轮询中的实现的主要内容,如果未能解决你的问题,请参考以下文章
如何从 jenkins 作业的 scm 轮询中排除 jenkins 文件
RabbitMQ02_简单模式Publish/Subscribe发布与订阅模式Routing路由模式Topics通配符模式Work模式-轮询公平
RabbitMQ02_简单模式Publish/Subscribe发布与订阅模式Routing路由模式Topics通配符模式Work模式-轮询公平