I have a basic model with a name Member- it contains membership information, such as first name, last name, email address, phone, etc. It also includes multi-valued fields that I need to store a collection - it Degreesand Affiliations.
The problem that I encounter when calling a method fetch()in my model is that there is an impedance mismatch between the base array and the collection objects that I have in my model. Since, parseby definition, it should return a hash that will be used in setinstead of actually setting the values, it is impossible for me to set my collections this way. For example, if I return a JavaScript object for Degrees, which looks something like this: {degrees: [{id: 1, title: "PhD"}]}then it converts my collection degreeinto a flat array. Here is my code:
window.Models.Member = Backbone.Model.extend({
url: '/api/member',
initialize: function() {
_.bindAll(this);
this.set('degrees', new window.Collections.DegreesList());
this.fetch();
},
parse: function(response) {
var setHash = {};
setHash.first_name = response.first_name;
setHash.last_name = response.last_name;
setHash.office_phone = response.office_phone;
setHash.degrees = _(response.degrees).each(function(item) {
return {id: item.id, title: item.title}
});
return setHash;
}
});
I could manually set collections in my parsing function, but it looks like it undermines the Backbone method and the hacker one.
EDIT: I temporarily solved the problem by doing the following:
parse: function(response) {
var setHash = {};
setHash.first_name = response.first_name;
setHash.last_name = response.last_name;
setHash.office_phone = response.office_phone;
this.get('degrees').reset( response.degrees );
return setHash;
}
, , , , . .