0
votes

In short i want to make a backbone deep collection of other collections and models

the structure is like this

[{
    mainCategory: "Something"
    subCategories: [
        {
            category: "SomethgingElse",
            labs: [
            {
                id: 1,
                title: "Title",
                description : "Lorem ipsum dolor sit amet"
                availablelanguages: ["fr","en"]
            },
            {
                id: 2,
                title: "Another Title",
                description : "Lorem ipsum dolor sit amet",
                availablelanguages: ["fr","en"]
            }]
        },
        {
            category: "Testing",
            labs: [
            {
                id: 1,
                title: "ZZZZ",
                description : "Lorem ipsum dolor sit amet"
                availablelanguages: ["ar","en"]
            },
            {
                id: 2,
                title: "VVVVV",
                description : "Lorem ipsum dolor sit amet",
                availablelanguages: ["ar","en"]
            }]
        }

    ]
}]

i defined some collections and models like the following

var Item = Backbone.Model.extend({
    defaults: {
        title : '',
        description: '',
        availableLangagues : []
    }
});
var Items = Backbone.Collection.extend({
    model: Item
});

var Category = Backbone.Model.extend({
    defaults: {
        categoryName: '',
        labsList: new Items()
    }
});
var Categories = Backbone.Collection.extend({
    model: Category
});
var TopCategory = Backbone.Model.extend({
    defaults: {
        topCategory: "",
        categories: new Categories()
    }
});
var TopCategories = Backbone.Collection.extend({
    model: TopCategory
});

My problem here i want to call fetch on the TopicCategories i want to populate everything , the fetch will return a JSON like passed in the example, but if i called fetch on TopCategories it will return the data but the array will be just normal JavaScript array not a backbone collection like i wanted in the defaults

1

1 Answers

2
votes

What you want to do is utilize your parse() function of your top model. In this modified, parse, what you do is tease out the different object/arrays from your response and transform them into the collections you desire. Example: parse() in the TopCategory model.

parse: function(response) {

    if (response.subCategories){

        if (!this.subCategories) {
            this.subCategories = new Categories(response.subCategories);
        } else {
            this.subCategories.reset(response.subCategories);
        }

        delete response.subCategories;
    }

    return response;
}

You'll do this pattern in the parse definition for each parent model that has some sort of backbone collection that you want to parse out.

This link might give you some more ideas as to how this all works.

Dealing with nested collections