gpt4 book ai didi

javascript - 主干集合未完全从 JSON 填充

转载 作者:行者123 更新时间:2023-12-02 16:42:29 25 4
gpt4 key购买 nike

我正在尝试从 JSON 数据填充 Backbone 集合。然而,在我尝试填充集合后,我只得到了其中一项,而我应该得到 12 项。你知道发生了什么吗?

JS:

(function ($) {


var Sponsor = Backbone.Model.extend({
defaults: {
link: "http://www.google.com",
photo: "http://placekitten.com/g/500/500"
}
});

var Sponsors = Backbone.Collection.extend({
model: Sponsor,
url: '../json/sponsors.json'
});

var SponsorView = Backbone.View.extend({
tagName: "li",
className: "sponsors-container",
template: $("#sponsorTemplate").html(),
render: function() {
var tmpl = _.template(this.template);

this.$el.html(tmpl(this.model.toJSON()));
return this;
}
});

var SponsorsView = Backbone.View.extend({
el: $(".sponsors"),

initialize: function() {
this.collection = new Sponsors();
this.collection.on("sync", this.render, this);
this.collection.fetch();
},

render: function() {
var that = this;
_.each(this.collection.models, function(item) {
that.renderSponsor(item)
}, this);
},

renderSponsor: function(item) {
var sponsorView = new SponsorView({
model: item
});
this.$el.append(sponsorView.render().el);
}
});
var sponsor = new SponsorsView();
} (jQuery));

JSON:

{
"sponsors":[
{"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"},
{"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"},
{"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"},
{"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"},
{"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"},
{"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"},
{"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"},
{"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"},
{"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"},
{"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"},
{"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"},
{"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"}
]
}

HTML:

<ul class="sponsors"></ul>
<script id="sponsorTemplate"type="text/template">

<a href="<%= link %>"><img src="<%= photo %>" /></a>

</script>

最佳答案

你的数据是一个对象而不是一个数组,这是 Backbone 集合所期望的。

您有两个选择:

  1. 将数据更改为数组。
  2. 添加 parse集合的方法,从结构中获取您需要的数组:
Backbone.Collection.extend({
parse: function (payload) {
return payload.sponsors
}
})

关于javascript - 主干集合未完全从 JSON 填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27391239/

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