新秀的问题,但我已经被困了23天了。下面是我的代码,用于显示来自外部阵列的项目列表。我的收藏没有呈现,在控制台中运行“ stations”时可以看到收藏中的项目。
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);
最佳答案
我认为杰克是对的-这样的事情可能对您有用:
var stations = new App.Collections.Stations();
stations.fetch({success: function(){
var stationsView = new App.Views.Stations({ collection: stations });
$('body').prepend(stationsView.$el);
}});
或对jqxhr对象deferred API使用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);
});