Backbone - 在渲染视图之前执行多个 fetch() [英] Backbone - performing multiple fetch() before rendering a view

查看:15
本文介绍了Backbone - 在渲染视图之前执行多个 fetch()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was wondering about the best pattern/approach here. This is a function in my router, so the user hits 'quotes/:id', but for that view to render, I need a list of their projects, customers and currencies. What would be the best way to make sure all 3 fetches() have occurred before trying to instantiate the quotesEdit view? Is it considered bad practice to grab all the information when the user clicks something?

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

推荐答案

我找到了 的组合jQuery deferreds 和 underscore 的 invoke 方法优雅地解决了这个问题:

I find a combination of jQuery deferreds and underscore's invoke method solves this elegantly:

//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...
});

这篇关于Backbone - 在渲染视图之前执行多个 fetch()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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