Barry
Barry

Reputation: 1587

BackboneJs: Creating multiple models in a collection from a nested object

{
    "code":"OK",
    "message":"Success",
    "errorFlag":"N",
    "errors":null,
    "data": {
        "images": {
            0: img0,
            1: img1,
            2: img2
        }
    }
}

This is a REST response and I wanted to put the "images" records in my collection and treat each individual records as models.

var Image.Model = Backbone.Model.extend({});
var Image.Collection = Backbone.Collection.extend({
    model: Image.Model,
    url: 'rest/url'
});
var images = new Image.TestCollection();
images.fetch();

How can I make the records inside the "images" be the only models of the image collections and put the code, message, errors etc. keys to another models or collections?

Thank you.

Upvotes: 3

Views: 971

Answers (1)

slobodan.blazeski
slobodan.blazeski

Reputation: 1040

Use http://backbonejs.org/#Collection-parse

// server.js
app.get('/api/data', function (req, res) {
    var result = {
        "code": "OK",
        "message": "Success",
        "errorFlag": "N",
        "errors": null,
        "data": {
            "images": {
                0: "img0",
                1: "img1",
                2: "img2"
            }
        }
    };
    res.json(result);
});

// client.js
var Image = Image || {};
Image.Model = Backbone.Model.extend({
});

Image.TestCollection = Backbone.Collection.extend({
    model: Image.Model,
    url: '/api/data',
    parse: function(response) {
        window.response =response;
        var images= [];
        for(var key in response.data.images){
            if(response.data.images.hasOwnProperty(key)){
                images.push(response.data.images[key]);
            }
        }
        return images;
    }
});
var images = new Image.TestCollection();
images.fetch();

P.S. It's usually bad idea to store data in the keys.

Upvotes: 2

Related Questions