我正在使用knockout-orderable插件,并且想保存排序顺序以重新显示表格内容。我可以这样做还是应该使用其他插件?
<tr>
<th data-bind="orderable: { collection: 'orders', field: 'name' }">Name</th>
<th data-bind="orderable: { collection: 'orders',field: 'group' }">Group</th>
</tr>
最佳答案
初始化后,orderable
绑定(bind)处理程序使用 2 个可观察对象扩展集合:orderField
和 orderDirection
。您只需订阅
那些可观察对象并将其数据保存到sessionStorage
(或localStorage
):
var vm = { orders: [...] };
// load recent values from storage to be passed as the defaults
vm.people.__lastOrderField = sessionStorage['ko__orderField'];
vm.people.__lastOrderDirection = sessionStorage['ko__orderDirection'];
// apply bindings first, in order to activate the plugin
ko.applyBindings(vm);
// subscribe to relevant fields once they're created by the plugin
vm.people.orderField.subscribe(function(val) { sessionStorage['ko__orderField'] = val; });
vm.people.orderDirection.subscribe(function(val) { sessionStorage['ko__orderDirection'] = val; });
在你的 HTML 中:
<a href="#" data-bind="orderable: {collection: 'people', field: 'firstName', defaultField: people.__lastOrderField === 'firstName', defaultDirection: people.__lastOrderDirection }">First Name</a>
<a href="#" data-bind="orderable: {collection: 'people', field: 'lastName', defaultField: people.__lastOrderField === 'lastName', defaultDirection: people.__lastOrderDirection }">Last Name</a>
<a href="#" data-bind="orderable: {collection: 'people', field: 'age', defaultField: people.__lastOrderField === 'age', defaultDirection: people.__lastOrderDirection }">Age</a>
参见Fiddle
关于knockout.js - 可 knockout 排序保存排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41431195/