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

时间:2012-08-22 06:43:27

标签: javascript asynchronous backbone.js callback

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

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

2 个答案:

答案 0 :(得分: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;
         }
    });

答案 1 :(得分:0)

考虑到您的设置,

dbasemans解决方案是正确的。但是,我宁愿将事件处理程序绑定到'reset'事件。这需要在获取之前进行处理。这个更干净,也可以在以后的应用程序运行时进一步提取。