Reputation: 36411
I have the following collection that gets data from an api:
var Data = Backbone.Collection.extend({
url: '/* api url - working */',
sync: function(method, model, options) {
options.timeout = 10000;
options.dataType = "jsonp";
return Backbone.sync(method, model, options);
}
});
And I want to display it in the view:
var MyView = Backbone.View.extend({
el : '.myview',
render : function () {
var data = new Data();
var that = this;
data.fetch({
success : function (data) {
console.log(arguments);
console.log(data);
var template = _.template( $('#temp').html(), {data: data.models} );
that.$el.html(template);
}
});
}
});
What I don't understand is that when I log arguments
I get the api data and it has a wieired structure: {0:child, 1:object\* contains the api data *\, 2:object}
but when I log data
I get only the child
I don't understand this structure, what am I missing and how do I get the api data out of it?
Upvotes: 2
Views: 1021
Reputation: 5060
Collection.fetch
is calling the success function you passed in with 3 arguments (from Backbone source):
success(collection, resp, options);
arguments
is a special local variable in all javascript functions. Check out this documentation.
So, logging arguments
is showing the 3 things passed into the success
function while logging data
is showing just the first thing passed in. Even though your function only has 1 parameter, three things were still passed to it.
The first thing passed to success
is the Backbone Collection itself. So, what you need to do with it depends on what your template looks like. It is common to pass just the JSON to the template function: _.template( $('#temp').html(), {data: data.toJSON()} )
. Then in the template, you would need to iterate over those JSON objects.
<% _.each(data, function(item){ %>
<div><%= item.foo %></div>
<% }); %>
Upvotes: 2