如何同步多个Backbone.js的抓取? [英] How to synchronize multiple Backbone.js fetches?

查看:91
本文介绍了如何同步多个Backbone.js的抓取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个有点新的Backbone.js的,但我已经一切pssed IM $ P $它可以为我做的,而且我努力学习的模式和最佳实践吧。

I’m a bit new to Backbone.js, but am already impressed by everything it can do for me, and am trying to learn the patterns and best practices now.

我有两个集合:

var CollA = Backbone.Collection.extend({
    model: ModelA,
    url: '/urlA'
});

var CollB = Backbone.Collection.extend({
    model: ModelB,
    url: '/urlB'
});

var collA = new CollA;
var collB = new CollB;

当加载我的应用程序,我需要获取无论是从服务器的这些藏品,并运行一些引导code时,它的保证,无论取已经完成。

When loading my app, I need to fetch both of these collections from the server, and run some bootstrap code when it’s guaranteed that both fetches have completed.

下面是我是如何做到的现在:

Here’s how I did it for now:

collA.fetch({success: function() {
    collB.fetch({success: function() {
        // run the needed code here.
    }});
}});

这工作的,所需要的code为保证只取两者成功完成后运行。这显然​​是低效的,虽然,因为取串行方式运行,此起彼伏。

This works, the needed code is guaranteed to run only after both fetches complete successfully. It is clearly inefficient though, because the fetches run serially, one after another.

什么会是一个更好的方式来做到这一点,并行运行的抓取,然后运行一些code,一旦两者取已成功完成?

What would be a better pattern to do this, to run the fetches in parallel and then run some code once both fetches have completed successfully?

推荐答案

如果你正在使用jQuery,使用

If you're using jQuery, use when:

$.when(collA.fetch(),collB.fetch()).done(function(){
    //success code here.
});

背景:

  • http://api.jquery.com/jQuery.when/
  • http://documentcloud.github.com/backbone/#Collection-fetch

您通过在一个或多个deferreds到 $。当。恰巧的jqXHR是集合返回实现诺言/递延接口,可以使用 $。当组合成一个新的承诺。该请求将主要是并发的(当然,尽可能JavaScript允许),当两者取成功传递到 .done 函数将只执行。

You pass in one or more deferreds to $.when. It so happens that the "jqXHR" that collections return implements the promise/Deferred interface that can be combined into a new promise using $.when. The requests will essentially be concurrent (well, as much as javascript allows) and the function passed to .done will execute only when both fetches are successful.

这篇关于如何同步多个Backbone.js的抓取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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