Knockout-ordeder保存排序顺序

时间:2017-01-02 17:50:08

标签: knockout.js

我正在使用knockout-orderable插件,并希望保存重新显示表格内容的排序顺序。我可以这样做,还是应该使用其他插件?

<tr>
    <th data-bind="orderable: { collection: 'orders', field: 'name' }">Name</th>
    <th data-bind="orderable: { collection: 'orders',field: 'group' }">Group</th>
</tr>

1 个答案:

答案 0 :(得分:1)

初始化后,orderable绑定处理程序正在使用2个可观察对象orderFieldorderDirection扩展集合。您只需subscribe即可观察到这些可观察数据,并将其数据保存到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