I am using the below code for handling sort functionality. It is working for me. But is there any way to make the code as common and so i can use it whenever needed.
<span class="sorting" data-bind="click: function(){ ui.items.sort(function(a,b){ return a.Username < b.Username ? -1 : 1; }); }">User Name</span>
<span class="sorting" data-bind="click: function(){ ui.items.sort(function(a,b){ return a.Firstname < b.Firstname ? -1 : 1; }); }">
First Name</span>
<span class="sorting" data-bind="click: function(){ ui.items.sort(function(a,b){ return a.Lastname < b.Lastname ? -1 : 1; }); }">
Last Name</span>
scripts
ui = new ListUI(config);
ko.applyBindings(ui);
var ListUI = function ListUIF(config) {
this.items = ko.observableArray([]);
}
var item = function itemF(data) {
var self = this;
self.Username = ko.observable(data.Username);
self.Firstname = ko.observable(data.Firstname);
self.Lastname = ko.observable(data.Lastname);
}
The code above is working fine, but i didn't want the sorting code to be repeated.
<span class="sorting" data-bind="click: function(){ ui.items.sort(function(a,b){ return a.Lastname < b.Lastname ? -1 : 1; }); }">
Last Name</span>
Instead i want something like this
<span class="sorting" data-bind="click: sortFunction">
Last Name</span>
var sortFunction = function sortFunctionF(a, b){
return a.Username < b.Username : -1 : 1; //How to make this common for other property also like Firstname, Lastname etc.
}
There's basically two options: Have three separate functions
sortByUsername
,sortByFirstname
andsortByLastname
, or you could do a custom binding that takes in additional information and sets up the sort.The second one could look something like this:
And then the custom binding for sortFunction:
Fiddle
Another option as mentioned by Joeseph would be to pass the property name into the click function, which would then return a function. I don't think this is as nice an option as the custom binding, but Here's a fiddle that does that:
And then your viewmodel would change to add the function: