Reputation: 4224
I'm learning Backbone, with a little example. I have a JSON url, the result looks like this :
{
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"
}
]
}
]
}
}
Now I want to get all the results into a HTML div, so I used this:
$(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>
The problem is that I don't know how to access the results
group in JSON response.
Thanks for your help.
Upvotes: 2
Views: 82
Reputation: 7556
you should use parse function to bind your model with results
property of result
element
var ProfileList = Backbone.Collection.extend({
model: Dataset,
url: 'profiles.json',
parse: function (response) {
return response.result.results;
}
});
Upvotes: 3