簡體   English   中英

如何使用$ .when作為回調函數?

[英]How to use $.when for a callback function?

我想說的是,當函數close()完成時,請運行該函數init()。 但這對我不起作用。

$.when(close(toolTip)).done(init(toolTip, anchor));

我沒有將$ .when用於與ajax相關的任何事情,只是試圖確保在調用init()之前完成close(),而且不,我不能在init()的結尾粘貼init()。 有任何想法嗎?

好的,這里是close()

var close = function (toolTip) {
    toolTip.fadeOut('fast', function (e) {
        if (typeof e !== 'undefined') {
            //Re-set values applied when initted
            var toolTipBd = toolTip.find('.bd:first');
            toolTip.css('width', '');
            toolTipBd.css('max-height', '');
            toolTip.css('max-height', '');
            toolTipBd.css('overflowY', '');
        }
    });
};

在close()中的任何地方都無法調用init()。

您的close()實現應如下所示:

var close = function (toolTip) {
    var d = $.Deferred();

    toolTip.fadeOut('fast', function (e) {
        if (typeof e !== 'undefined') {
            //Re-set values applied when initted
            var toolTipBd = toolTip.find('.bd:first');
            toolTip.css('width', '');
            toolTipBd.css('max-height', '');
            toolTip.css('max-height', '');
            toolTipBd.css('overflowY', '');
        }

        d.resolve();
    });

    return d.promise();
};

$.when作品與Deferred 它返回一個新的Deferred當所有這將解決Deferred的你提供的決心。

由於close()似乎沒有返回Promise,因此when可以立即解決(根據when()文檔when()

但是,如果close()是同步的,則根本不需要when() 如果它異步的,則需要返回Promise ,並在動畫或其他完成時解決它;

function close(what) {
    var promise = jQuery.Deferred();

    what.fadeOut('slow', function () {
        promise.resolve();
    });

    return promise.promise();
}

...但是$.when只涉及1個諾言時,您仍然不需要$.when .。 $.when僅在多個諾言同時起作用時才有用。

close(toolTip).done(function () {
    init(toolTip, anchor);
});

還要注意, done(init(tooltip, anchor))將立即調用init ,並將該函數調用的結果傳遞給done() 相反,您需要傳遞一個函數來完成。 由於init需要參數,因此我們通過引入匿名函數來解決此問題。 如果init不需要任何參數,它就很簡單:

close(toolTip).done(init);

只需返回工具提示:

return toolTip.fadeOut(...

如果出於任何原因選擇了多個元素,則使用回調來解析延遲的對象可能會導致奇怪的結果。

這是.promise ,因為jQuery對象具有.promise方法,該方法在被調用時返回一個promise對象,該對象將在所有活動動畫完成時進行解析。 $.when .promise在所有傳入的參數上調用.promise時。

您還需要以不同的方式調用init,例如,

$.when(close(toolTip)).done(function(){
    init(toolTip, anchor);
});

而且,正如其他人所指出的,您可以將其縮短為

close(toolTip).promise().done(function(){
    init(toolTip, anchor);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM