我正在使用淘汰赛绑定。
在最初创建表并设置绑定后,我尝试添加新行或更新现有条目,然后更新表。
但是当数据更新时,KnockOut会给我错误消息"您不能多次将绑定应用于同一元素"。
这是我的代码
ko.applyBindings(viewModel);
$('.tree').treegrid();
答案 0 :(得分:1)
根据错误,无法重新绑定已绑定的元素。清除现有绑定然后重新绑定也不是进行更新的理想方式。
根据我们昨晚的聊天情况,我相信您正在尝试更新表格,然后显示反映更新。
相反,请考虑以下示例来更新现有的KnockOut表。
它不使用jQuery或TreeGrid,但添加它们不应该太多工作。我觉得删除它们简化了这个例子,使其更加清晰。
否则,这应该是动态添加,删除和更改表条目的一个很好的例子(而不仅仅是初始化)。
// Function to create KnockOut view
var ViewModel = function() {
var self = this;
// This is row 0.
self.rows = ko.observableArray([
{name:'DefaultEntry', number:-1}
]);
}
// Function to create a row entry
var Row = function(name, number) {
var self = this;
self.name = ko.observable(name);
self.number = ko.observable(number);
};
// Create the view and apply bindings.
vm = new ViewModel();
ko.applyBindings(vm);
// Add more rows live
vm.rows.push(new Row('OldTest',10)); // Row 1, Row 0 was defined earlier.
vm.rows.push(new Row('Sam',1010));
vm.rows.push(new Row('Max',1523));
// Change a specific entry ("OldTest" -> "NewTest")
// Note: vm.rows() returns an array of rows in the table, and [1] selects the index number of Row 1.
// vm.rows()[1] returns the index which KO can reference of row 1
vm.rows.replace(vm.rows()[1], new Row('NewTest',9999));
// Remove last entry
vm.rows.pop();
// Remove all rows
vm.rows.removeAll();
// Add new row
vm.rows.push(new Row('Bob',2000));
vm.rows.push(new Row('Tom',3000));
vm.rows.push(new Row('Sally',4000));
vm.rows.push(new Row('Lou',5000));
vm.rows.push(new Row('Zack',6000));
// Remove all rows where name == 'Tom'
vm.rows.remove( function (person) { return person.name() == "Tom"; } )
// Remove row 2-3 (Lou and Zack)
garbageData = vm.rows.splice(2,3);
// In the above example, garbageData contains an array of the removed rows.
// Splice also works as "vm.rows.splice(2,3);"
// You do not need to save the array returned by splice.
// Final output:
// Bob 2000
// Sally 4000
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<table>
<thead>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
</thead>
<tbody data-bind="foreach: rows">
<tr>
<td><input class="input-small" data-bind="value: name"/></td>
<td><input class="input-small" data-bind="value: number"/></td>
</tr>
</tbody>
</table>
我还添加了KnockoutJS网站,该网站显示了可用于操作这些行的其他方法:KnockoutJS - Observable Arrays
答案 1 :(得分:0)
您应该先清理节点并应用敲除绑定。
ko.cleanNode($('#html-element-id')[0]);
ko.applyBindings(new ViewModel(modelData{}), $('#html-element-id')[0]);