3

我正在使用 Backbone.js 显示来自 API 请求的项目(站)列表。

我的问题似乎被问了很多,我已经尽可能多地解决了其他问题的解决方案,但我仍然有一个问题。

下面是代码:

(function($) {

    _.templateSettings = {
    interpolate: /\{\{(.+?)\}\}/g
    };
//  models
    var Station = Backbone.Model.extend({
        urlRoot: '../api/admin/stations/',
        idAttribute: "_id",
        defaults: {
            _id: null,
            country: 'ZA'
        }
    });

//  collections
    var StationList = Backbone.Collection.extend({
        model: Station,
        url: '../api/admin/stations/'
});

//  views
/*
 * Station View
 */
    var StationView = Backbone.View.extend({
        tagName: 'article',
        className:  'station-container',
        template: $("#stationListTemplate").html(),

        render: function() {
            this.$el.html(this.template(this.model.toJSON()));
            return this;
        }
    });

/*
 * Master View (Station List)
 */
    var StationListView = Backbone.View.extend({
        el: $("#stationListView"),

        initialize: function() {
            this.collection = new StationList();
            this.collection.fetch({
                success: this.render()
            });
        },
        render: function() {
            var that = this;
            console.log(this.collection.models); // RETURNS EMPTY ARRAY
            _.each(this.collection.models, function (item) {
// NOTHING HAPPENS AS THE ARRAY IS EMPTY
                that.renderStation(item);
            }, this);
        },
        renderStation: function (item) {
            var stationView = new StationView({
                model: item
            });
            console.log(stationView);
            this.$el.append(stationView.render().el);
        }
    });

//  load views
    var _stationList = new StationListView;
} (jQuery));

我已经在上面的 CAPS 中添加了我收到错误的注释。当我console.log(that)console.log(this.collection)我可以看到该集合,但在那之后我无法立即访问它的模型。

我只是不知道我做错了什么导致我无法访问模型。任何帮助将不胜感激

4

1 回答 1

0

我引用你的代码:

success: this.render()

我很确定你应该写

success:this.render

或者

success:function(){
 this.render()
}

因为当您定义成功回调(并根据您的代码执行它)时,尚未获取该集合。虽然可能还有其他错误,但这一个很明显

于 2012-12-09T21:49:07.660 回答