使用带有承诺的jQuery加载 [英] Using jQuery load with promises

查看:92
本文介绍了使用带有承诺的jQuery加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在尝试绕过 deferred 不,所以考虑到这一点,我对如何执行以下操作提出了疑问.

I'm still trying to wrap my head around deferred and what not, so with this in mind I have a question on how to do the following.

我的团队和我有3个单独的.load()方法,每个方法都抓取一个特定的模板并将其附加到同一容器中.每次加载花费的时间可能与您想象的不同,因此,在加载内容时,它以阶梯式"方式加载(先是1,然后是2,然后是3).我想使用 deferred对象,然后等到它们完成所有操作,然后同时添加它们以删除阶梯"操作.

My team and I have 3 separate .load() methods that each go grab a specific template and append that to the same container. Each load takes a different amount of time as you might think, so when the content loads, it loads in a 'stair step' fashion (1, then 2, then 3). I'd like to make use of deferred objects and wait until they are all done, then append them at the same time to remove the 'stair step' action.

$('<div>').load(baseInfoTemplate, function () {
    var baseData = {
        // build some object
    };

    $.tmpl(this, baseData).appendTo($generalContainer);
});

所有三个呼叫均与上述呼叫相似.

All three calls are similar to the call above.

我该如何实现?

推荐答案

$.load()不是为与Deferred对象一起使用而设计的,它还专门用于立即将内容放入页面中.

$.load() isn't designed for use with Deferred objects, and also it is intended specifically to drop stuff into the page immediately.

要解决后一个问题,您要么必须将整个容器呈现在DOM外部,然后在它们全部完成后放入它,要么需要累加三个结果,然后一次性将它们全部放入.

To solve that latter problem you either have to render the entire container outside the DOM, and then drop it in when they're all done, or you need to accumulate the three results and then put them all in in one go.

以下过程使用后一种方法:

The process below uses the latter approach:

  1. 改为使用$.get(),并创建由$.get()

将每个$.get()的返回片段也存储在数组中

Store the return fragments from each $.get() in an array too

使用$.when.apply($, myArray).done(function() { ... })应用模板并将其放入DOM

Use $.when.apply($, myArray).done(function() { ... }) to apply the templates and put them into the DOM

请参见 http://jsfiddle.net/alnitak/WW3ja/

这篇关于使用带有承诺的jQuery加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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