1

我有一个使用主干的应用程序,但是每当我调用fetch()集合的方法时,它都会返回未定义:

// App

(function () {

    window.app = {};
    app.collections = {};
    app.models = {};
    app.views = {};

    $(function () {
        app.collections.complaintTypes = new app.collections.ComplaintTypesCollection();
        app.views.complaintTypesView = new app.views.ComplaintTypesView({ collection: app.collections.complaintTypes });
    });

})();

// Collections

(function (collections, model) {
    collections.ComplaintTypesCollection = Backbone.Collection.extend({
        initialize: function () {
            this.fetch();
        },
        model: model,
        url: '/api/ComplaintTypes'
    });
})(app.collections, app.models.ComplaintType);

// Models

(function (models) {
    models.ComplaintType = Backbone.Model.extend({
        idAttribute: 'ComplaintTypeId'
    });
})(app.models);


// Views

(function (views) {
    views.ComplaintTypesView = Backbone.View.extend({
        initialize: function () {
            this.collection.on('reset', this.render, this);
        },
        render: function () {
            console.log(this.collection);
        }
    });
})(app.views);

但这不返回任何东西?如果我使用 fiddler 并转到我的 URL:/api/ComplaintTypes 我确实会检索数据,所以我不确定我在这里做错了什么?

4

3 回答 3

3

删除集合文件中的“模型”行对我有用。

于 2012-12-05T13:44:26.333 回答
1

获取是异步的。如果需要获取结果,则需要传递一个“成功”处理程序,即:

function myHandler(models) {

}
...
this.fetch({success: myHandler});
于 2012-09-07T08:25:46.883 回答
1

我认为问题在于您在尚未获取集合时创建了视图(因为 JS 的异步行为)。试试这个方法:

$(function () {
    app.collections.complaintTypes = new app.collections.ComplaintTypesCollection();
    app.collections.complaintTypes.fetch({success:function(){
        app.views.complaintTypesView = new app.views.ComplaintTypesView({ collection: app.collections.complaintTypes });
    }});      
});

并从您的集合中删除初始化功能。

于 2012-09-07T08:27:52.447 回答