Ryuhei Irie
Ryuhei Irie

Reputation: 51

Nested Model in Backbone.js

I want to map JSON having hierarchical structure onto Model. I can map the data at a top hierarchy onto Model. However, I can't map it onto Model which nested the element which I nested.

JSON

{
    "attr1":"data1",
    "chi1": {
        "attr1":"chi1_data"
    },
    "list1":[
        {"name":"name1"},
        {"name":"name2"}
    ]
}

JavaScript

var Child2 = Backbone.Model.extend({
    fun1:function() {
        alert("this is Child2");
    }
});

var List1 = Backbone.Collection.extend({
    url: "list1",
    model: Child2,
    fun1:function() {
        alert("this is List1");
    }
});

var Child1 = Backbone.Model.extend({
});

var Root1 = Backbone.Model.extend({
    url: "sample.json",
    defaults : {
        list1 : new List1,
        chi1 : new Child1,
    }
});

var View1 = Backbone.View.extend({
    el: "#friends",
    events: {
        "click button": "sample"
    },
    initialize: function() {
        this.root1 = new Root1();
    },
    sample: function() {
        this.root1.fetch({
            success: function(model) {
                // this is success
                alert(model.get("attr1"));

                // this is error
                alert(model.get("list1").fun1());

                // this is error too.
                model.get("list1").each(function(attr) {
                    alert(attr.fun1());
                });
            },
            error: function(model, res) { 
                alert("error: " + res.status);
            }
        });
    },
});

Upvotes: 2

Views: 2159

Answers (2)

Ryuhei Irie
Ryuhei Irie

Reputation: 51

thank you jcreamer.

backbone-nested plugin seems to be different from what I want to do. I can realize the nest of the model. In using parse function.

// it is able to get "chi1_data"
new Child2(JSON.parse(JSON.stringify(resp["chi1"]))).get("attr1")

// it is able to get "name2"
new Child2(JSON.parse(JSON.stringify(new List1(JSON.parse(JSON.stringify(resp["list1"]))).get(2)))).get("name")

I found Backbone-relational plug in. I will try this

https://github.com/PaulUithol/Backbone-relational

Upvotes: 1

jcreamer898
jcreamer898

Reputation: 8189

You might want to take a look at this plugin.

http://documentup.com/afeld/backbone-nested/

Might not be exactly what you want, but it could at least point you in the right direction.

The other thing you can do is override the parse method on your model...

parse: function(resp){
    // And setup the model using the raw resp
    // The resp data is your json from the server and will 
    // be used to setup the model. So overriding parse, you can
    // setup the model exactly they way you want.
    return resp;
}

Upvotes: 3

Related Questions