0

I have this model structure in my mind:

var app = app || {};

// Caratteristica
app.Attribute = Backbone.Model.extend({
    defaults: {     
        name: '',
        selected: false 
    }
});

app.Attributes = Backbone.Collection.extend({
    model: app.Attribute
});

// Tipo Caratteristica
app.AttributeCategory = Backbone.Model.extend({
    defaults: {     
        name: '', 
        attributes: new app.Attributes() 
    }
});

app.AttributeCategories = Backbone.Collection.extend({
    model: app.AttributeCategory, 
    url: '/ajax/attributes.cfm'
});

My API in '/ajax/attributes.cfm' will give me a response like that:

[
    {
        "id": "1",
        "name": "Type1",
        "attributes": [
            {
                "id": "1",
                "name": "Attribute1"
            },
            {
                "id": "2",
                "name": "Attribute2"
            },
            {
                "id": "3",
                "name": "Attribute3"
            }
        ]
    },
    {
        "id": "2",
        "name": "Type2",
        "attributes": [
            {
                "id": "1234",
                "name": "Attribute1234"
            },
            {
                "id": "2567",
                "name": "Attribute2567"
            }
        ]
    }
]

My question is: will this json data be parsed correctly into my nested data structure? I mean I want to end up having two app.AttributeCategory items in my app.AttributeCategories collection. Each of these two items must then have its attributes property filled with the corresponding app.Attributes collection.

If the answer was NO, how would I override the parse() function for achieving that result?

Fabio B.
  • 9,138
  • 25
  • 105
  • 177

2 Answers2

1

I did it like this:

// Tipo Caratteristica
app.AttributeCategory = Backbone.Model.extend({
    defaults: {     
        name: ''
    },
    initialize: function(options) {
        this.set('attributes', new app.Attributes(options.attributes));
        Backbone.Model.prototype.apply(this, arguments);
    }
});

But better use RationalModel for set up relations betweens models

Sergey
  • 5,208
  • 25
  • 36
0

You can create the collection inside an initialize method in your AttributeCategory model, like this:

app.AttributeCategory = Backbone.Model.extend({

    ...

    initialize: function () {
      this.set('attributes', new app.Attributes(this.get('attributes')));
    }
});
ejosafat
  • 401
  • 2
  • 12