jQuery 中的自定义事件? [英] Custom events in jQuery?

查看:25
本文介绍了jQuery 中的自定义事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找有关如何以最佳方式在 jquery 中实现自定义事件处理的一些意见.我知道如何从 dom 元素(如点击"等)中连接事件,但我正在构建一个小型 javascript 库/插件来处理一些预览功能.

我有一个脚本正在运行,用于根据我得到的一组规则和数据/用户输入更新 dom 元素中的一些文本,但现在我需要在该脚本不可能知道的其他元素中显示相同的文本的.我需要的是一个很好的模式来以某种方式观察这个脚本产生所需的文本.

那我该怎么做呢?我是否忽略了 jquery 中的一些内置功能来引发/处理用户事件,或者我是否需要一些 jquery 插件来做到这一点?您认为处理此问题的最佳方法/插件是什么?

解决方案

看看这个:

(转载自过期博客页面http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/ 基于 http://web.archive.org/web/20130120010146/http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/)

<小时>

使用 jQuery 发布/订阅

2008 年 6 月 17 日

为了编写与 Google Gears 离线功能集成的 jQuery UI,我一直在尝试使用一些代码来使用 jQuery 轮询网络连接状态.

网络检测对象

基本前提很简单.我们创建了一个网络检测对象的实例,它将定期轮询 URL.如果这些 HTTP 请求失败,我们可以假设网络连接已丢失,或者当前无法访问服务器.

$.networkDetection = function(url,interval){var url = url;var 间隔 = 间隔;在线=假;this.StartPolling = function(){this.StopPolling();this.timer = setInterval(poll, interval);};this.StopPolling = function(){clearInterval(this.timer);};this.setPollInterval= 函数(i){间隔 = i;};this.getOnlineStatus = function(){在线返回;};函数轮询(){$.ajax({类型:POST",网址:网址,数据类型:文本",错误:函数(){在线=假;$(document).trigger('status.networkDetection',[false]);},成功:函数(){在线 = 真;$(document).trigger('status.networkDetection',[true]);}});};};

您可以在此处查看演示.将浏览器设置为离线工作,看看会发生什么......不,这不是很令人兴奋.

触发和绑定

令人兴奋的(或者至少是让我兴奋的)是通过应用程序传递状态的方法.我偶然发现了一种使用 jQuery 的 trigger 和 bind 方法来实现发布/订阅系统的主要未讨论的方法.

演示代码比它需要的更钝.网络检测对象将状态"事件发布到主动侦听它们的文档,然后将通知"事件发布给所有订阅者(稍后会详细介绍).这背后的原因是,在现实世界的应用程序中,可能会有更多的逻辑控制何时以及如何发布通知"事件.

$(document).bind("status.networkDetection", function(e, status){//订阅者可以有多个类的命名空间订阅者 = $('.subscriber.networkDetection');//甚至向订阅者发布notify.networkDetectionsubscribers.trigger("notify.networkDetection", [状态])/*其他基于网络连接的逻辑可以放在这里使用谷歌齿轮离线存储等也许会触发一些其他事件*/});

由于 jQuery 以 DOM 为中心的方法,事件被发布到(触发)DOM 元素.这可以是一般事件的窗口或文档对象,或者您可以使用选择器生成 jQuery 对象.我在演示中采用的方法是创建一个几乎命名空间的方法来定义订阅者.

要成为订阅者的 DOM 元素被简单地归类为订阅者"和网络检测".然后,我们可以通过在 $(.subscriber.networkDetection")<上触发通知事件,仅将事件发布到这些元素(演示中只有一个)/p>

#notifier div 是 .subscriber.networkDetection 订阅者组的一部分,然后绑定了一个匿名函数,有效地充当听众.

$('#notifier').bind("notify.networkDetection",function(e, online){//下面简单演示一下通知程序 = $(this);如果(在线){if (!notifier.hasClass("online")){$(这个).addClass("在线").removeClass("离线").text("在线");}}别的{如果(!notifier.hasClass(离线")){$(这个).addClass("离线").removeClass("在线").text("离线");}};});

那么,你去吧.这一切都非常冗长,我的例子一点也不令人兴奋.它也没有展示你可以用这些方法做的任何有趣的事情,但如果有人有兴趣挖掘源代码,请随意.所有代码都内联在演示页面的头部

I'm looking for some input on how to implement custom eventhandling in jquery the best way. I know how to hook up events from the dom elements like 'click' etc, but I'm building a tiny javascript library/plugin to handle some preview functionality.

I've got a script running to update some text in a dom element from a set of rules and data/user input I got, but now I need that same text shown in other elements that this script can't possibly know of. What I need is a good pattern to somehow observe this script producing the needed text.

So how do I do this? Did I overlook some builtin functionality in jquery to raise/handle user events or do I need some jquery plugin to do it? What do you think is the best way/plugin to handle this?

解决方案

Take a look at this:

(reprinted from the expired blog page http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/ based on the archived version at http://web.archive.org/web/20130120010146/http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/)


Publish / Subscribe With jQuery

June 17th, 2008

With a view to writing a jQuery UI integrated with the offline functionality of Google Gears i’ve been toying with some code to poll for network connection status using jQuery.

The Network Detection Object

The basic premise is very simple. We create an instance of a network detection object which will poll a URL at regular intervals. Should these HTTP requests fail we can assume that network connectivity has been lost, or the server is simply unreachable at the current time.

$.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]);
            }
        });
    };
};

You can view the demo here. Set your browser to work offline and see what happens…. no, it’s not very exciting.

Trigger and Bind

What is exciting though (or at least what is exciting me) is the method by which the status gets relayed through the application. I’ve stumbled upon a largely un-discussed method of implementing a pub/sub system using jQuery’s trigger and bind methods.

The demo code is more obtuse than it need to be. The network detection object publishes ’status ‘events to the document which actively listens for them and in turn publishes ‘notify’ events to all subscribers (more on those later). The reasoning behind this is that in a real world application there would probably be some more logic controlling when and how the ‘notify’ events are published.

$(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
    */
});

Because of jQuery’s DOM centric approach events are published to (triggered on) DOM elements. This can be the window or document object for general events or you can generate a jQuery object using a selector. The approach i’ve taken with the demo is to create an almost namespaced approach to defining subscribers.

DOM elements which are to be subscribers are classed simply with "subscriber" and "networkDetection". We can then publish events only to these elements (of which there is only one in the demo) by triggering a notify event on $(".subscriber.networkDetection")

The #notifier div which is part of the .subscriber.networkDetection group of subscribers then has an anonymous function bound to it, effectively acting as a listener.

$('#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");
        }
    };
});

So, there you go. It’s all pretty verbose and my example isn’t at all exciting. It also doesn’t showcase anything interesting you could do with these methods, but if anyone’s at all interested to dig through the source feel free. All the code is inline in the head of the demo page

这篇关于jQuery 中的自定义事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆