我正在使用 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)
我可以看到该集合,但在那之后我无法立即访问它的模型。
我只是不知道我做错了什么导致我无法访问模型。任何帮助将不胜感激