Reputation: 2971
I'm using the Backbone collections's reset method to bootstrap a bunch of JSON data straight into the collection at page load time.
The documentation gives some clue that this might be the case, but when I do this neither the Collection's or Models' parse methods are fired. Which is really annoying.
Here is some sample code:
var ablefutures = {};
ablefutures.category = Backbone.Model.extend({
idAttribute : 'categoryId',
parse : function(response)
{
debugger;
response.categoryDetailItems = new ablefutures.categoryDetailItems(response.categoryDetailItems);
return response;
}
});
ablefutures.categories = Backbone.Collection.extend({
model: ablefutures.category,
url: '../api/categoriesRouter.php',
parse : function(response)
{
debugger;
return response
}
});
categories = new ablefutures.categories();
categories.reset([{"categoryId":1,"name":"Eyewear","heroText":"<div>The complete <span class=\"stand-out\">eyewear<\/span> solution<\/div><div class=\"subText\">Eye protection for clinicians and patients.<\/div>","categoryDetailItems":[{"categoryDetailId":1,"description":"gdfsgdfgdfgdfgdf"}],"created":null,"lastUpdated":null,"status":1}]);
category = categories.get(1);
$('#category').html(category.get('categoryId'));
See the below fiddle: http://jsfiddle.net/JonRed/zW68M/2/
I would hope that both the 'debugger' statements would be hit here, but as you can see, neither are. The documentation states that 'parse' is only fired on the collection's fetch method, but this would involve a second ajax call which I simply don't need.
Can anyone suggest a technique I can use to get the collection's reset method to fire the parse methods?
Thanks,
Upvotes: 2
Views: 160
Reputation: 434675
Collection#reset
takes a second options
argument. The documentation doesn't mention it but you can pass parse: true
in the options
to get reset
to call parse
:
categories.reset([...], { parse: true });
Minimal Demo: http://jsfiddle.net/ambiguous/2BJdq/
Update Version of your fiddle: http://jsfiddle.net/ambiguous/whb7m/
reset
ends up calling Collection#set
to do most of the heavy lifting and it passes the options
along when set
is called. set
doesn't document the parse: true
behavior either but you can see it in the code:
set: function(models, options) {
//...
if (options.parse) models = this.parse(models, options);
To be honest, I took a guess, based on other parts of the API, that parse: true
in the options might work and tried it, then I went to find justification by tracing through the docs and source code.
Upvotes: 4