SRAMPI
SRAMPI

Reputation: 373

Knockout-orderable save sort order

I am using the knockout-orderable plug-in and would like to save the sort order for re-displaying the table content. Can I do that or should I use another plug-in?

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

Upvotes: 2

Views: 243

Answers (1)

haim770
haim770

Reputation: 49113

Upon initializing, the orderable binding-handler is extending the collection with 2 observables, orderField and orderDirection. You can simply subscribe to those observable and persist their data to the sessionStorage (or 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; });

And in your 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>

See Fiddle

Upvotes: 2

Related Questions