gpt4 book ai didi

javascript - Backbone.js 中的嵌套模型

转载 作者:行者123 更新时间:2023-11-29 18:29:29 26 4
gpt4 key购买 nike

我想将具有层次结构的 JSON 映射到模型上。我可以将顶层的数据映射到模型上。但是,我无法将它映射到嵌套了我嵌套的元素的模型。

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

最佳答案

您可能想看看这个插件。

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

关于javascript - Backbone.js 中的嵌套模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9756365/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com