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

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

问题描述

我仍在努力解决deferred 什么不是,所以考虑到这一点,我有一个关于如何执行以下操作的问题.

我和我的团队有 3 个独立的 .load() 方法,每个方法都会抓取一个特定的模板并将其附加到同一个容器中.正如您想象的那样,每次加载需要不同的时间,因此当内容加载时,它以阶梯式"方式加载(1,然后是 2,然后是 3).我想使用 deferred 对象 和等待它们全部完成,然后同时附加它们以删除阶梯"动作.

$('

').load(baseInfoTemplate, function () {var baseData = {//构建一些对象};$.tmpl(this, baseData).appendTo($generalContainer);});

所有三个调用都与上面的调用相似.

我怎样才能做到这一点?

解决方案

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

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

下面的过程使用后一种方法:

  1. 使用 $.get() 代替,并创建 $.get() 返回的 jqXHR 对象数组

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

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

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

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.

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.

How can I achieve this?

解决方案

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

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. Use $.get() instead, and create an array of the jqXHR objects returned by $.get()

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

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

See http://jsfiddle.net/alnitak/WW3ja/

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

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