2012-03-18 122 views
2

我想將具有分層結構的JSON映射到模型上。我可以將頂層的數據映射到模型上。但是,我無法將它映射到嵌套嵌套元素的Model上。Backbone.js中的嵌套模型

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); 
      } 
     }); 
    }, 
}); 

回答

3

你可能想看看這個插件。

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

也許不是正是你想要的,但它至少可以點你在正確的方向。

你可以做的另一件事是覆蓋的解析方法對你的模型...

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

謝謝jcreamer。

骨幹嵌套插件似乎與我想要做的不同。 我可以實現模型的嵌套。在使用解析函數。

// 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") 

我發現骨幹關係插件。我會嘗試這個

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