我正在学习Backbone,只举一个例子。我有一个JSON网址,结果如下:
{
help: "Help",
success: true,
result: {
count: 13,
results: [
{
name: "Name 1",
description: "Desc 1",
resources: [
{
img: "url.jpg"
}
]
},
{
name: "Name 2",
description: "Desc 2",
resources: [
{
img: "url2.jpg"
}
]
}
]
}
}
现在我想将所有结果都放到HTML div中,所以我使用了这个:
$(function() {
var Dataset = Backbone.Model.extend();
var ProfileList = Backbone.Collection.extend({
model: Dataset,
url: 'profiles.json'
});
var ProfileView = Backbone.View.extend({
el: "section#block-block-5",
template: _.template($('#profileTemplate').html()),
render: function(eventName) {
_.each(this.model.models, function(profile){
var profileTemplate = this.template(profile.toJSON());
$(this.el).append(profileTemplate);
}, this);
return this;
}
});
var profiles = new ProfileList();
var profilesView = new ProfileView({model: profiles});
profiles.fetch({
success: function(){
profilesView.render();
}
});
});
<script id="profileTemplate" type="text/template">
<div class="profile">
<div class="info">
<div class="name">
<%= name %>
</div>
<div class="description">
<%= description %>
</div>
<div class="image">
<%= resources.url %>
</div>
</div>
</div>
</script>
问题是我不知道如何在JSON响应中访问results
组。
感谢您的帮助。
答案 0 :(得分:3)
你应该使用parse函数将你的模型与results
元素的result
属性绑定
var ProfileList = Backbone.Collection.extend({
model: Dataset,
url: 'profiles.json',
parse: function (response) {
return response.result.results;
}
});