16

我想知道这里的最佳模式/方法。这是我的路由器中的一个功能,因此用户点击“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]
        }));
    }
4

3 回答 3

40

我发现jQuery deferreds和 underscore 的组合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...
});
于 2013-02-19T16:55:08.133 回答
20

承诺!特别是 jQuery.when

你可以这样做:

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

jQuery.ajax(以及通过扩展骨干提取)返回一个承诺,$.when一旦多个承诺得到解决,您就可以使用它来设置回调函数。

于 2013-02-19T16:55:22.063 回答
4

Backbonefetch返回一个 jQueryDeferred对象(一个承诺)。所以你可以使用 jQuery 的when 函数来等待所有的 Promise 解决:


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]
    }));

  };

}

我在这里写了一些关于 Promise 和 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

于 2013-02-19T16:55:29.737 回答