我有数据表,希望能够过滤行中的数据,数据来自服务并通过淘汰来绑定:
<table class="table bordered hovered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody data-bind="foreach: usersList">
<tr>
<td data-bind="text: Id"></td>
<td data-bind="text: UserName"></td>
</tr>
</tbody>
</table>
function getUsers() {
$.getJSON('/api/aspnetusers', null, function (users) {
ViewModel.usersList.pushAll(users);
});
}
getUsers();
$(function () {
$('.table').DataTable();
});
在输入过滤器输入后,我总是得到:
No data available in table
答案 0 :(得分:0)
这可能是一个计时问题,请在初始化DataTables之前尝试等待数据加载:
$.getJSON('/api/aspnetusers', null, function (users) {
ViewModel.usersList.pushAll(users);
}).done(function(){ $('.table').DataTable(); });
答案 1 :(得分:0)
这是做到这一点的方法......我已经做了一个jsfiddle显示:
为了使其工作,我必须为原始的knockout foreach绑定定义添加两个回调方法。我目前正试图让这些事件进入淘汰赛的最新版本。我需要添加一个beforeRenderAll和afterRenderAll回调来销毁数据表并在敲除foreach绑定后添加html重新初始化数据表。这就像一个魅力JSFiddle显示它有一个完全可编辑的jquery数据表,通过淘汰绑定到ViewModel。
ko.bindingHandlers.DataTablesForEach = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
return ko.bindingHandlers.foreach.init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var value = ko.unwrap(valueAccessor()),
key = "DataTablesForEach_Initialized";
var newValue = function () {
return {
data: value.data || value,
beforeRenderAll: function(el, index, data){
if (ko.utils.domData.get(element, key)) {
$(element).closest('table').DataTable().destroy();
}
},
afterRenderAll: function (el, index, data) {
$(element).closest('table').DataTable(value.options);
}
};
};
ko.bindingHandlers.foreach.update(element, newValue, allBindingsAccessor, viewModel, bindingContext);
//if we have not previously marked this as initialized and there is currently items in the array, then cache on the element that it has been initialized
if (!ko.utils.domData.get(element, key) && (value.data || value.length)) {
ko.utils.domData.set(element, key, true);
}
return { controlsDescendantBindings: true };
}
};