渲染视图多个异步阿贾克斯后,与骨干网要求 [英] Rendering a view after multiple asynchronous ajax calls with Backbone

查看:147
本文介绍了渲染视图多个异步阿贾克斯后,与骨干网要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种骨干观点,我想呈现HTML后2异步调用过:

I have a backbone view and I want to render html AFTER 2 asynchronous calls have been:

initialize: function (model, options) {        
    team.fetch({
                success: function (collection) { 
                  //do some things            
           });

    goal.fetch({
                success: function (collection) { 
                  //do some things          
           });

    this.render();
}

    render: function () {
        this.$el.html(template());
        return this;
    }

显然,与code以上,HTML模板将返回前/期间Ajax调用。通常情况下,当只有一个Ajax调用,我做的:

Obviously, with the code above, the html template will be returned before/during the ajax calls. Normally, when just one ajax call, I do:

initialize: function (model, options) {      
    var that = this;
    team.fetch({
                success: function (collection) { 
                  //do some things     
                          that.render();
           });


}

    render: function () {
        this.$el.html(template());
        return this;
    }

什么是最优雅的方式与多个Ajax调用这样做呢?

What's the most elegant way for doing this with multiple ajax calls?

推荐答案

我会使用 JQuery的递延的实施,特别是 $。当 。这可让您只需要一个动作,当多个异步操作完成。使用这样的:

I would use the JQuery Deferred implementation, specifically $.when. This lets you take an action only when multiple async operations have completed. Use it like this:

var ajax1 = team.fetch({ ... });
var ajax2 = goal.fetch({ ... });

$.when( ajax1, ajax2 ).done( this.render );

修改

由于@muistooshort所指出的,你还必须结合渲染,以便它能够调用正确的上下文(否则渲染将引用Ajax对象而不是视图对象):

As @muistooshort points out, you also have to bind render, so that it gets called with the correct context (otherwise this inside render would refer to the ajax object instead of the view object):

_.bind(this.render, this);

这篇关于渲染视图多个异步阿贾克斯后,与骨干网要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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