我在添加和刪除Json數據時遇到了問題。使用Knockout添加和刪除嵌套的Json數據js
首先我從服務器獲取模型,然後將其轉換爲JSON數據。 並且需要添加或刪除json數據。
這裏是我的JSON數據:
{
"$id": "1",
"Number": "000100029304",
"Title": "Test Title",
"Status": "Ready",
"StatusDate": null,
"Author": null,
"UpdatedDate": "2012-12-12T12:12:12",
"Comments": "test comment",
"Type": {
"$id": "2",
"Title": "Type #1",
"UpdatedDate": "2011-11-11T11:1:11",
"Name": "AAA",
"Documents": [
{
"$ref": "1"
}
],
"ID": 100
},
"DocOwner": {
"$id": "3",
"Name": "CEO",
"Title": "General Director",
"Documents": [
{
"$ref": "1"
}
],
"ID": 1
},
"Links": [
{
"$id": "4",
"DocumentId": 1234,
"Name": "Some file1.xls",
"Path": "\\\\mycomp\\folder\\Some file1.xls",
"Type": 0,
"Document": {
"$ref": "1"
},
"ID": 200
},
{
"$id": "5",
"DocumentId": 1234,
"Name": "Some file2.xls",
"Path": "\\\\mycomp\\folder\\Some file2.xls",
"Type": 0,
"Document": {
"$ref": "1"
},
"ID": 201
},
{
"$id": "6",
"DocumentId": 1234,
"Name": "Some file3.xls",
"Path": "\\\\mycomp\\folder\\Some file3.xls",
"Type": 0,
"Document": {
"$ref": "1"
},
"ID": 202
},
],
"ID": 1234
}
正如你可以看到有一些鏈接,我不能添加或刪除新的鏈接。
我配置淘汰賽這樣的:
var Link = function (data) {
var self = this;
if (data != null) {
ko.mapping.fromJS(data, {}, self);
} else {
self.ID = ko.observable();
self.DocumentId = ko.observable();
self.Name = ko.observable();
self.Path = ko.observable();
self.Type = ko.observable();
self.Document = ko.observableArray();
}
}
var DocViewModel = function (data) {
var self = this;
self.doc = dataModel;
//if (data != null) {
// ko.mapping.fromJS(data, { Links: linkMapping }, self);
//} else {
// self.doc.Links = ko.observableArray();
//}
self.addLink = function() {
self.doc.Links.push(new Link({
ID: null,
DocumentId: null,
Name: "New link",
Path: null,
Type: null,
Document: null
}));
}
self.removeLink = function (Link) {
self.doc.Links.remove(Link);
}
self.saveJson = function() {
var myJson = ko.mapping.toJSON(self);
$("#txt").val(myJson);
}
}
var linkMapping = {
create: function (options) {
return new Link(options.data);
}
}
$(document).ready(function() {
var viewModel = new DocViewModel();
ko.applyBindings(viewModel);
});
但它不工作。我如何配置淘汰賽來修復它?
預先感謝您。 https://jsfiddle.net/pa3zcvae/
你在else部分作爲一個可觀察數組,但在json對象中是一個對象。 – Bindrid
試過,但沒有發生 'self.doc = ko.observableArray([]);' 'self.doc(數據模型);' – John
其中處於self.doc.Links.remove(鏈路)除去;界定? – Bindrid