gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:09:18 25 4
gpt4 key购买 nike

菜鸟问题,但我已经被难住了 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);
}});

或者使用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);
});

关于javascript - 来自外部 JSON 文件的主干集合未呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24964155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com