如何在自定义事件中使用jQuery Deferred? [英] How to use jQuery Deferred with custom events?

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

问题描述

我有两个抽象的过程(例如,使用不公开其内部结构的显示模块模式在js对象中进行管理)会触发

I have two abstracted processes (e.g. managed within js objects using the revealing module pattern that do not expose their internals) that fire custom events when they complete. I want to perform an action when both custom events have fired.

jQuery 1.5中新的延迟逻辑似乎是一种理想的方法要对此进行管理,除了when()方法采用了返回了promise()的Deferred对象(或普通js对象,但是when()立即完成而不是等待完成,这对我来说是没有用的).

The new Deferred logic in jQuery 1.5 seems like it would be an ideal way to manage this, except that the when() method takes Deferred objects that return a promise() (or normal js objects, but then when() completes immediately instead of waiting, which is useless to me).

理想情况下,我想执行以下操作:

Ideally I would like to do something like:

//execute when both customevent1 and customevent2 have been fired
$.when('customevent1 customevent2').done(function(){
  //do something
});

结合这两种技术的最佳方法是什么?

What would be the best way to marry these two techniques?

推荐答案

http://jsfiddle.net/ch47n/

我创建了一个小插件,该插件创建了一个新的jQuery.fn.when方法.

I created a small plugin that creates a new jQuery.fn.when method.

语法是:

jQuery( "whatever" ).when( "event1 event2..." ).done( callback );

它在内部广泛使用jQuery.when()并确保在解决之前已对集合中的所有元素触发了所有事件.

It uses jQuery.when() extensively internally and ensures that all events have been triggered on all elements in the collection before resolving.

下面的实际插件代码:

( function( $ ) {

    $.fn.when = function( events ) {

        var deferred, $element, elemIndex, eventIndex;

        // Get the list of events
        events = events.split( /\s+/g );

        // We will store one deferred per event and per element
        var deferreds = [];

        // For each element
        for( elemIndex = 0; elemIndex < this.length; elemIndex++ ) {
            $element = $( this[ elemIndex ] );
            // For each event
            for ( eventIndex = 0; eventIndex < events.length; eventIndex++ ) {
                // Store a Deferred...
                deferreds.push(( deferred = $.Deferred() ));
                // ... that is resolved when the event is fired on this element
                $element.one( events[ eventIndex ], deferred.resolve );
            }
        }

        // Return a promise resolved once all events fired on all elements
        return $.when.apply( null, deferreds );
    };

} )( jQuery );

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

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