外部JSON文件的骨干集合无法呈现

时间:2014-07-25 20:41:49

标签: javascript json backbone.js

新秀问题,但我已经被困了23天了。下面是我的代码,用于显示外部阵列中的项目列表。我的收藏品没有渲染,我可以在运行' station'时看到集合中的项目。在控制台中。

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

1 个答案:

答案 0 :(得分:2)

我认为杰克是对的 - 这样的事情对你有用:

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

或者使用deferred API作为jqxhr对象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);
});