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

ben*_*e89 16 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]
        }));
    }
Run Code Online (Sandbox Code Playgroud)

jev*_*lio 40

我发现jQuery延迟的组合和下划线的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...
});
Run Code Online (Sandbox Code Playgroud)

  • 默认情况下,使用`GET` http方法进行提取.令人惊讶的是我可以写`_.invoke([quotes,projects,currency],'fetch',{type:'POST'})` (3认同)
  • 我认为这个答案有点过于聪明,因为它本身就是好事.你必须要理解`_.invoke`,`fetch`,`when`和`apply`的行为.尽管@ mrappleton的答案非常清楚,即使对于那些甚至只对"$ .when"有模糊理解的人也是如此. (3认同)

mra*_*ton 20

承诺!特别是jQuery.when

你可以这样做:

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

jQuery.ajax(以及扩展主干fetch)返回一个promise,你可以$.when在解决多个promise后设置一个回调函数.