I’m using Backbone.js to display a list of items (stations) from an API request.
My question has been asked a lot it seems, I have gone through as many as possible of the other questions’ solutions, but I still have a problem.
Here is code below:
(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));
I have added comments above in CAPS for where I get an error. When I console.log(that) or console.log(this.collection) I can see the collection, but I can’t access its models immediately after that.
I just don’t know what I am doing wrong that’s making me unable to access the model. Any help would be highly apreciated
i quote your code :
i’m pretty sure you should either write
or
because by the time you define success callback (and execute it according to your code ), the collection hasn’t been fetched yet. There may be other errors though , but this one is pretty obvious