Backbone - 在渲染视图之前执行多次获取()

时间:2013-02-19 16:46:07

标签: backbone.js

我想知道这里最好的模式/方法。这是我的路由器中的一个功能,因此用户点击'quotes /:id',但是为了呈现该视图,我需要一个他们的项目,客户和货币的列表。在尝试实例化quotesEdit视图之前,确保所有3个fetches()都已发生的最佳方法是什么?在用户点击某些内容时获取所有信息被认为是不好的做法吗?

    quotesEdit: function(id) {
        kf.Collections.quotes = kf.Collections.quotes || new kf.Collections.Quotes();
        kf.Collections.projects = kf.Collections.projects || new kf.Collections.Projects();
        kf.Collections.currencies = kf.Collections.currencies || new kf.Collections.Currencies();
        //do a fetch() for the 3 above
        kf.Collections.customers = kf.Collections.customers || new kf.Collections.Customers();
        var quote = kf.Collections.quotes.where({Id: parseInt(id, 10)});
        kf.Utils.ViewManager.swap('sectionPrimary', new kf.Views.section({
          section: 'quotesEdit',
          model: quote[0]
        }));
    }

3 个答案:

答案 0 :(得分:40)

我发现jQuery deferreds和下划线invoke方法的组合可以很好地解决这个问题:

//call fetch on the three collections, and keep their promises
var complete = _.invoke([quotes, projects, currencies], 'fetch');

//when all of them are complete...
$.when.apply($, complete).done(function() {
   //all ready and good to go...
});

答案 1 :(得分:20)

承诺!具体来说是jQuery.when

您可以这样做:

$.when(
  kf.Collections.quotes.fetch(),
  kf.Collections.projects.fetch(),
  kf.Collections.currencies.fetch()
).then(function(){
  // render your view.
});

jQuery.ajax(以及扩展主干fetch)返回一个promise,一旦多个promise被解析,你就可以使用$.when来设置一个回调函数。

答案 2 :(得分:4)

Backbone的fetch返回一个jQuery Deferred对象(一个promise)。因此,您可以使用jQuery的when function等待所有要解决的承诺:


quotesEdit: function(id) {
  kf.Collections.quotes = kf.Collections.quotes || new kf.Collections.Quotes();
  kf.Collections.projects = kf.Collections.projects || new kf.Collections.Projects();
  kf.Collections.currencies = kf.Collections.currencies || new kf.Collections.Currencies();

  //do a fetch() for the 3 above
  var quotePromise = kf.Collections.quotes.fetch();
  var projectsPromise = kf.Collections.projects.fetch();
  var currenciesPromise = kf.collections.currencies.fetch();

  // wait for them to all return
  $.when(quotePromise, projectsPromise, currenciesPromise).then(function(){

    // do stuff here, now that all three have resolved / returned

    kf.Collections.customers = kf.Collections.customers || new kf.Collections.Customers();
    var quote = kf.Collections.quotes.where({Id: parseInt(id, 10)});
    kf.Utils.ViewManager.swap('sectionPrimary', new kf.Views.section({
      section: 'quotesEdit',
      model: quote[0]
    }));

  };

}

我在这里写了一些关于promises和jQuery的文章:

http://lostechies.com/derickbailey/2012/03/27/providing-synchronous-asynchronous-flexibility-with-jquery-when/

http://lostechies.com/derickbailey/2012/07/19/want-to-build-win8winjs-apps-you-need-to-understand-promises/

第二个链接仍然有效,尽管主要主题是Win8 JS

相关问题