获取结果未定义(主干.js)

fetch result is undefined (Backbone.js)

本文关键字:js 主干 结果 未定义 获取      更新时间:2023-09-26
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值......但它即将"未定义"。 有什么想法我错了吗?

fetch 方法是异步的,因此在使用它时尚未分配output变量。 尝试将render调用放在成功回调中:

var self = this;
stuff.fetch({
        success: function (collection, response) {
            console.log(response);
            output=response;
            self.render(output);
            return response;
         }
    });
考虑到

您的设置,dbasemans解决方案是正确的。但是,我宁愿将事件处理程序绑定到"重置"事件。这需要在获取之前进行。这更干净,并且也适用于稍后在应用程序运行时进一步获取。