How can I correctly parse the Backbone model to include collections?

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;

        // 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 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;     
}

, , , , . .

+5
1

, , .

  • , JSON: degreesData
  • initialize : this.degrees = new Degrees().reset( this.get( "degreesData" ) );
+2

All Articles