我是淘汰插件的新手,我正在尝试使用此插件构建一个commentthread。当一个子注释绑定到父注释时,我遇到了一些问题,期望的json字符串化对象应该是下面的东西;
[
{
CreatedBy: "user 1",
CreatedOn: Date(),
Description: "comment 1",
ChildFeeds: [
{
CreatedBy: "user 2",
CreatedOn: Date(),
Description: "comment 1-1"
},
{
CreatedBy: "user 3",
CreatedOn: Date(),
Description: "comment 1-2"
},
{
CreatedBy: "user 4",
CreatedOn: Date(),
Description: "comment 1-3"
}
]
},
{
CreatedBy: "user 5",
CreatedOn: Date(),
Description: "comment 2",
ChildFeeds: [
{
CreatedBy: "user 6",
CreatedOn: Date(),
Description: "comment 2-1"
},
{
CreatedBy: "user 7",
CreatedOn: Date(),
Description: "comment 2-2"
}
]
},
]
但是当我运行代码时,获取以下数据而不是上述数据的结构。
[
{
"CreatedBy": "user 1",
"CreatedOn": "Mon Jan 02 2012 15:50:51 GMT+0200 (Turkey Standard Time)",
"Description": "comment 1",
"ChildFeeds": [
{
"ChildFeeds": [
{
"CreatedBy": "user 2",
"CreatedOn": "Mon Jan 02 2012 15:50:51 GMT+0200 (Turkey Standard Time)",
"Description": "comment 1-1"
},
{
"CreatedBy": "user 3",
"CreatedOn": "Mon Jan 02 2012 15:50:51 GMT+0200 (Turkey Standard Time)",
"Description": "comment 1-2"
},
{
"CreatedBy": "user 4",
"CreatedOn": "Mon Jan 02 2012 15:50:51 GMT+0200 (Turkey Standard Time)",
"Description": "comment 1-3"
}
]
}
]
},
{
"CreatedBy": "user 5",
"CreatedOn": "Mon Jan 02 2012 15:50:51 GMT+0200 (Turkey Standard Time)",
"Description": "comment 2",
"ChildFeeds": [
{
"ChildFeeds": [
{
"CreatedBy": "user 6",
"CreatedOn": "Mon Jan 02 2012 15:50:51 GMT+0200 (Turkey Standard Time)",
"Description": "comment 2-1"
},
{
"CreatedBy": "user 7",
"CreatedOn": "Mon Jan 02 2012 15:50:51 GMT+0200 (Turkey Standard Time)",
"Description": "comment 2-2"
}
]
}
]
}
]
在这里你会注意到,由于编码错误,不幸的是我为每个父对象复制了两次ChildFeeds对象数组..你可以从这里找到代码http://jsfiddle.net/6qAmu/5/
实现此问题的最佳方法是什么?
谢谢
答案 0 :(得分:2)
现在,您的ChildFeedModel
是一个包含ChildFeeds
observableArray的对象,因此当您将此内容分配给ChildFeeds
上的wallfeedsmodel
媒体资源时,您最终会得到加倍ChildFeeds
。
一种选择是让你的ChildFeedsModel
实际上是一个observableArray。因此,您将创建一个observableArray,使用任何其他方法/属性扩展它,然后返回它。
类似的东西:
var childFeedModel = function(ChildFeeds) {
var result = ko.observableArray();
result.addChildFeed = function(tempChildFeed) {
result.push({
CreatedBy: tempChildFeed.CreatedBy,
CreatedOn: tempChildFeed.CreatedOn,
Description: tempChildFeed.Description
});
};
ko.utils.arrayForEach(ChildFeeds, function(feed) {
result.addChildFeed(feed);
});
return result;
};
我将它更改为以小写字母开头,因为在创建一个字母时它现在不需要new
语句(它总是返回一个新的observableArray)。
现在,在您的wallfeedsmodel
中,您只需将其指定为:
return {
CreatedBy: singlefeed.CreatedBy,
CreatedOn: singlefeed.CreatedOn,
Description: singlefeed.Description,
ChildFeeds: childFeedModel(singlefeed.ChildFeeds)
};