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

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

问题描述

我正在寻找有关如何在jquery中实现自定义事件处理的一些输入方法。我知道如何连接诸如点击等dom元素的事件,但是我正在构建一个小型的JavaScript库/插件来处理一些预览功能。

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我有一个脚本运行,以从一组规则和数据/用户输入中更新dom元素中的一些文本,但现在我需要与该脚本不可能知道的其他元素中显示的相同的文本。我需要的是一个很好的模式,以某种方式观察这个脚本产生所需的文本。

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.

那么我该怎么做?我是否忽略了jquery中的一些内置函数来提升/处理用户事件,还是需要一些jQuery插件呢?你认为最好的方法/插件来处理这个问题?

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?

推荐答案

看看这个:

(从过期的博客页面转载 http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/ 根据 http:// / />>

(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/)

2008年6月17日

June 17th, 2008

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

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.

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

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.

虽然(或至少是什么令人兴奋的是)通过应用程序转发状态的方法。我绊倒了使用jQuery的触发器和绑定方法实现一个pub / sub系统的一个很大程度上没有讨论过的方法。

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

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

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元素简单地使用订阅者和networkDetection。然后,我们可以通过触发 $(。subscriber.networkDetection)

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")

#notifier code> .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天全站免登陆