0

下面的代码看起来好像在获取完成之前触发了 AccItemList 集合上的“重置”事件。为此,控制台的输出如下...

渲染

0

取来的

0

...所以“渲染”在集合中没有任何模型之前被调用,这显然是错误的,但同样令人困惑的是,即使在 fetch 成功回调中,集合中似乎也没有任何模型。我也尝试在路由器初始化程序中实例化 AccItemList 集合,但这并没有什么不同。我确定我缺少一些基本的东西,请帮忙,这让我发疯!

$(function () {

    var AccItem = Backbone.Model.extend({
        defaults: {}
    });

    var AccItemList = Backbone.Collection.extend({
        model: AccItem,
        url: "/Dashboard/Accommodation",
        parse: function (response) {
            this.add(response.AccItems);
        }
    });

    var AccListView = Backbone.View.extend({
        el: $("#temp"),
        initialize: function () {
            _.bindAll(this, 'render', 'renderAccItem');
            this.collection = new AccItemList();
            this.collection.on('reset', this.render);
            var that = this;
            that.collection.fetch({
                success: function () {
                    console.log("fetched");
                    console.log(that.collection.models.length);
                }
            });
        },
        render: function () {
            var that = this;
            console.log("rendering");
            console.log(this.collection.models.length);
        }
    });

    var App = Backbone.Router.extend({
        routes: {
            "": "index"
        },
        index: function () {
        },
        init: function () {
            var accItemView = new AccListView();
        }
    });

    var app = new App();
    app.init();

});
4

1 回答 1

6

在中,您手动添加模型,除了Backbone 文档状态AccItemList.parse外不返回任何内容

解析 集合.解析(响应)

每当服务器返回集合的模型时,Backbone 都会在 fetch 中调用 parse。该函数传递原始响应对象,并应返回要添加到集合中的模型属性数组。默认实现是无操作的,只是通过 JSON 响应。如果您需要使用预先存在的 API 或更好的响应命名空间,请覆盖此选项。请注意,之后,如果您的模型类已经有一个解析函数,它将针对每个获取的模型运行。

尝试

var AccItemList = Backbone.Collection.extend({
    model: AccItem,
    url: "/Dashboard/Accommodation",
    parse: function (response) {
        return response.AccItems;
    }
});

模拟您的代码和修改版本的小提琴:http: //jsfiddle.net/nikoshr/Q25dp/

调用重置事件和成功回调的顺序取决于 Backbone 源代码中的实际实现。请参阅http://documentcloud.github.com/backbone/docs/backbone.html#section-98

var success = options.success;
options.success = function(resp, status, xhr) {
    //reset call
    collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);

    //custom success call
    if (success) success(collection, resp);
};
于 2012-09-19T09:12:58.873 回答