I have two functions that call fetch on a Backbone model. The first one creates a new instance of a model using an id and calls fetch(), the second one retrieves an existing model instance from a collection using id and calls fetch(). In the first one, the model's parse function is triggered, but not on the second one...and I don't know why.
First one (triggers parse)
App.fetchItemById = function (id) {
App.myItem = new App.Item({id: id});
App.myItem.fetch({
traditional: true,
data: {
elements: 'all',
format:'json',
},
success: function(){
App.myItemView = new App.ItemView({
el: $('#active-item'),
model: App.myItem,
});
App.myItemView.render();
}
});
};
Second one (doesn't trigger parse)
App.fetchItemFromCollectionById = function (id) {
App.myItem = App.myItemCollection.get(id);
App.myItem.fetch({
traditional: true,
data: {
elements: 'all',
format:'json',
},
success: function(){
App.myItemView = new App.ItemView({
el: $('#active-item'),
model: App.myItem,
});
App.myItemView.render();
}
});
};
All of the documentation I've read says that the model's parse function is ALWAYS called on fetch.
Anyone know why parse isn't triggered on the second one?
Here's the model definition:
App.Item = Backbone.Model.extend({
urlRoot: '/api/v1/item/',
defaults: {
},
initialize: function(){
},
parse : function(response){
console.log('parsing');
if (response.stat) {
if (response.content.subitems) {
this.set(‘subitems’, new App.SubitemList(response.content.subitems, {parse:true}));
delete response.content.subitems;
this
}
return response.content;
} else {
return response;
}
},
});
FIXED, THANKS TO EMILE & COREY - SOLUTION BELOW
Turns out, when I first load the App.MyItemCollection, the models in the collection were just generic models, not correctly cast as instances of App.Item. Adding "model: App.Item" to the collection definition solved the problem. See below:
ORIGINAL
App.ItemList = Backbone.Collection.extend({
url: '/api/v1/item/',
parse : function(response){
if (response.stat) {
return _.map(response.content, function(model, id) {
model.id = id;
return model;
});
}
}
});
UPDATED, SOLVED PROBLEM
App.ItemList = Backbone.Collection.extend({
url: '/api/v1/item/',
model: App.Item,
parse : function(response){
if (response.stat) {
return _.map(response.content, function(model, id) {
model.id = id;
return model;
});
}
}
});