【发布时间】:2021-01-10 23:32:30
【问题描述】:
我有一个视图模型,它通过敲除绑定到模式弹出窗口。 modal 有一个按钮,用于获取数据(实际上是从服务器获取 ajax,但只是从本示例的一些静态代码),然后将该数据绑定到表并将其转换为 DataTable。 Knockout 添加了 DataTable。
获取数据并正确呈现数据表。但是,我需要能够通过单击行来选择行,而且这些数据绑定语句在获取数据后似乎没有得到处理。
这是 HTML:
<a href="#" class="btn btn-default" data-bind="click: initArray">Init Table</a>
<a href="#" class="btn btn-default" data-bind="click: swapArray">Swap Table Array</a>
<div id="datatablescontainer" style="border: 1px solid green;"></div>
<div id="datatableshidden" style="display:none;" >
<table class="datatable">
<thead>
<tr>
<th>first</th>
<th>last</th>
</tr>
</thead>
<tbody data-bind="foreach: rows">
<tr data-bind="click: $parent.testAlert">
<td align="center" data-bind="text: firstName"></td>
<td align="center" data-bind="text: lastName"></td>
</tr>
</tbody>
</table>
</div>
这是脚本:
// Here's my data model
var ViewModel = function() {
this.rows = ko.observable(null);
this.datatableinstance = null;
this.initArray = function() {
var rowsource1 = [
new ChildVM({ "firstName" : "John", "lastName" : "Smith"}),
new ChildVM({ "firstName" : "Mary", "lastName" : "Smith" })
];
this.redraw(rowsource1);
}
this.swapArray = function() {
var rowsource2 = [
new ChildVM({ "firstName" : "James", "lastName" : "Smith" }),
new ChildVM({ "firstName" : "Alice", "lastName" : "Smith" }),
new ChildVM({ "firstName" : "Doug", "lastName" : "Smith" })
];
this.redraw(rowsource2);
}
this.redraw = function(rowsource) {
this.rows(rowsource);
var options = { paging: false, "order": [[0, "desc"]], "searching":true };
var datatablescontainer = $('#datatablescontainer');
var html = $('#datatableshidden').html();
//Destroy datatable
if (this.datatableinstance) {
this.datatableinstance.destroy();
datatablescontainer.empty();
}
//Recreate datatable
datatablescontainer.html(html);
this.datatableinstance = datatablescontainer.find('table.datatable').DataTable(options);
}
this.testAlert = function() {
alert('test');
}
};
var ChildVM = function(data) {
var self = this;
if(data != null)
{
self.firstName = data.firstName;
self.lastName = data.lastName;
}
this.testAlert = function() {
alert('test');
}
}
ko.applyBindings(new ViewModel()); // This makes Knockout get to work
这是一个小提琴(根据此问题的另一篇文章定制)。
*更新小提琴 https://jsfiddle.net/websitewill/rgsw2odp/17/
我在主 VM 和 ChildVM 上有 testClick。我已经尝试使用 $parent.testClick 并且只是在表行数据绑定中使用 testClick 。两者都没有被调用(但也没有报告错误)。
感谢您的帮助。 会
【问题讨论】:
标签: knockout.js datatables knockout-mvc