如何再次将绑定重新应用于同一元素



我正在使用挖空绑定。

最初创建表并设置绑定后,我正在尝试添加新行或更新现有条目,然后更新表。

但是当数据更新时,KnockOut给了我错误消息"您不能多次将绑定应用于同一元素"。

这是我的代码

 ko.applyBindings(viewModel);
 $('.tree').treegrid();

根据错误,无法重新绑定已绑定的元素。清除现有绑定然后重新绑定也不是执行更新的理想方法。

根据我们昨晚的聊天,我相信您正在尝试更新表格,然后显示反射性更新。

相反,请考虑以下示例来更新现有的挖空表。

它没有使用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 - 可观察数组

您应该首先清理节点并应用挖空绑定。

ko.cleanNode($('#html-element-id')[0]);
ko.applyBindings(new ViewModel(modelData{}), $('#html-element-id')[0]);

最新更新