我有一些带有可观察数组的嵌套视图模型,并且无法成功添加到任何嵌套数组中。在顶层添加工作正常。我做了很多阅读和摆弄,试图解决我做错的事情,但无济于事。
层次结构如下:Queue-->Files-->Claims-->Lines
我可以将新文件添加到队列中,但无法添加新声明(通过文件和队列尝试)
任何想法我做错了什么? http://jsfiddle.net/bxfXd/254/
更新:下面的所有答案都指向我的核心问题——在我的可观察数组中使用原始数据而不是实例化模型。使用工作代码更新小提琴:http: //jsfiddle.net/7cDmg/1/
HTML:
<h2>
<span data-bind="text: name"></span>
<a href='javascript:' data-bind="click: addFile">AddFile</a>
</h2>
<div data-bind="foreach: files">
<h3>File: <span data-bind="text: name"></span> (<span data-bind="text: id"></span>)
<a href='javascript:' data-bind="click: $data.addClaim">AddClaimViaFile</a>
<a href='javascript:' data-bind="click: $root.addClaim">AddClaimViaQueue</a></h3>
<div data-bind='foreach: claims'>
<h3 data-bind="text: ud"></h3>
<table border=1>
<thead>
<td>id</td> <td>procedure</td> <td>charge</td>
</thead>
<tbody data-bind='foreach: lines'>
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: procedure"></td>
<td data-bind="text: charge"></td>
</tr>
</tbody>
</table>
</div>
</div>
JavaScript:
var line1 = { id: 1, procedure: "Amputate", charge: 50 };
var line2 = { id: 2, procedure: "Bandage", charge: 10};
var claim1 = { ud: '1234E123', charge: 123.50, lines: [line1,line2] };
var claim2 = { ud: '1234E222', charge: 333.51, lines: [line2,line2] };
var file1 = { id: 1, name: "Test1.txt", claims: [claim2] };
var file2 = { id: 2, name: "Test2.txt", claims: [] };
var queue = { id: 1, name: "JoesQueue", files: [file1,file2] };
function Line(data) {
this.id = ko.observable(data.id);
this.procedure = ko.observable(data.procedure);
this.charge = ko.observable(data.charge);
}
function Claim(data) {
this.ud = ko.observable(data.ud);
this.charge = ko.observable(data.charge);
this.lines = ko.observableArray(data.lines);
}
function File(data) {
var self=this;
self.id = ko.observable(data.id);
self.name = ko.observable(data.name);
self.claims = ko.observableArray(data.claims);
self.addClaim = function(file) { //this never gets called.. Why?
alert("File.addClaims");
self.claims.push(claim1);
}
}
function Queue(data) {
this.id = ko.observable(data.id);
this.name = ko.observable(data.name);
this.files = ko.observableArray(data.files);
this.addClaim = function(file) {
alert("Queue.addClaim");
console.log(file);
file.claims.push(claim1); //This line gets hit, but no claims get added..Why?
};
this.addFile = function() {
alert("Queue.addFile");
this.files.push(file2); //Works - adding seems to only work at the top level :(
}
}
$(function () {
ko.applyBindings(new Queue(queue));
});
</p>