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

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

问题描述

我对 Backbone.js 有点陌生,但它可以为我做的一切已经给我留下了深刻的印象,我现在正在努力学习模式和最佳实践.

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;

在加载我的应用程序时,我需要从服务器获取这两个集合,并在保证两个获取都已完成时运行一些引导代码.

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.

这是我现在的做法:

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

这是有效的,需要的代码保证只有在两次提取都成功完成后才能运行.但是,这显然是低效的,因为提取是一个接一个地串行运行.

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.

执行此操作的更好模式是并行运行提取,然后在两次提取均成功完成后运行一些代码?

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,请使用 when:

If you're using jQuery, use when:

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

背景:

您将一个或多个延迟传递给 $.when.碰巧的是,集合返回的jqXHR"实现了 promise/Deferred 接口,该接口可以使用 $.when 组合成一个新的 promise.请求基本上是并发的(好吧,在 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天全站免登陆