Reputation: 357
Rookie question, but i've been stumped for 23 days now. Below is my code to display a list of items from an external array. My collection is not rendering, I can see the items in the collection when running 'stations' in the console.
window.App = {
Views: {},
Models: {},
Collections: {}
}
window.template = function(id){
return _.template( $('#' + id).html() );
};
App.Models.Station = Backbone.Model.extend({
defaults: {
name: 'Station',
bikes: 20
}
});
App.Collections.Stations = Backbone.Collection.extend({
model: App.Models.Station,
url: 'http://api.citybik.es/dublinbikes.json',
parse : function(response){
return response;
}
});
App.Views.Station = Backbone.View.extend({
tagName: 'li',
initialize: function(){
this.render();
},
render: function(){
this.$el.html( this.model.get('name') + ': ' + this.model.get('bikes') + ' bikes available');
return this;
}
});
App.Views.Stations = Backbone.View.extend({
tagName: 'ul',
initialize: function(){
this.render();
},
render: function(){
this.collection.each(this.addOne, this);
},
addOne: function(station){
var stationView = new App.Views.Station({ model: station });
this.$el.append(stationView.render().el);
}
});
var stations = new App.Collections.Stations();
stations.fetch();
var stationsView = new App.Views.Stations({ collection: stations });
$('body').prepend(stationsView.$el);
Upvotes: 0
Views: 148
Reputation: 9789
I think jack is right - something like this may work for you:
var stations = new App.Collections.Stations();
stations.fetch({success: function(){
var stationsView = new App.Views.Stations({ collection: stations });
$('body').prepend(stationsView.$el);
}});
Or using the deferred API for the jqxhr object returned from fetch
:
var stations = new App.Collections.Stations();
var stationsLoaded = stations.fetch();
stationsLoaded.done(function(){
var stationsView = new App.Views.Stations({ collection: stations });
$('body').prepend(stationsView.$el);
});
Upvotes: 2