繁体   English   中英

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

[英]Backbone collection from external JSON file not rendering

新秀问题,但是我已经陷入困境了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);
}});

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM