来自外部JSON文件的主干集合不呈现



新手问题,但我已经被难住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);

我认为jack是对的——像这样的东西可能对你有用:

var stations = new App.Collections.Stations();
stations.fetch({success: function(){
  var stationsView = new App.Views.Stations({ collection: stations });
  $('body').prepend(stationsView.$el);
}});

或者为fetch返回的jqxhr对象使用延迟API:

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);
});

最新更新