获取结果未定义(Backbone.js)

gho*_*... 2 javascript asynchronous callback backbone.js

var ListView = Backbone.View.extend({
    el: $('hello'),
    initialize: function() {
        var stuff = new FieldCollection();
        var output;
        stuff.parse();
        stuff.fetch({
            success: function (collection, response) {
                console.log(response);
                output=response;
                return response;
             }
        });
        this.render(output);
   },
   render:function(output){
        console.log(output);
        $(this.el).append("<button id='add'>hiii</button>");
        $(this.el).append("<button id='removeAll'>Remove all list item</button>");
    }
});
Run Code Online (Sandbox Code Playgroud)

在这里,我试图在output变量中捕获响应的值......但它正在出现'未定义'.任何我错的想法?

McG*_*gle 5

fetch方法是异步的,因此在output您使用它时不会分配变量.尝试将render调用置于success-callback中:

var self = this;
stuff.fetch({
        success: function (collection, response) {
            console.log(response);
            output=response;
            self.render(output);
            return response;
         }
    });
Run Code Online (Sandbox Code Playgroud)