I have a backbone model called Member
- this contains membership data such as first name, last name, email, phone, etc. It also includes multi-valued fields that I need to keep as collections - these are Degrees
and Affiliations
.
The issue I am running into when calling the fetch()
method in my model is that there's an impedance mismatch of sorts between a basic array, and the collection objects I have in my model. Since parse
by definition is supposed to return a hash to be used in set
rather than actually setting values, it is impossible for me to set my collections this way. For instance - if I return a JavaScript object for Degrees
that looks something like the following: {degrees: [{id: 1, title: "PhD"}]}
, then this converts my degree
collection into 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;
// When this is run, this.get('degrees') will now return a flat array rather than a DegreesList collection
setHash.degrees = _(response.degrees).each(function(item) {
return {id: item.id, title: item.title}
});
return setHash;
}
});
I could manually set the collections in my parse function, but that seems like its subverting the Backbone way, and hacky.
EDIT: I've 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;
}
I doubt this is the optimal solution, but it certainly works for now. I'm open to better suggestions.
I use exactly the same workaround you are proposing except with a few changes.
degreesData
initialize
I create the collection like this: this.degrees = new Degrees().reset( this.get( "degreesData" ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With