javascript - Dynamically accessing properties of knockoutjs observable array -
i using below code handling sort functionality. working me. there way make code common , can use 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 working fine, didn't want sorting code 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 want 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 make common other property firstname, lastname etc. }
there's 2 options: have 3 separate functions sortbyusername
, sortbyfirstname
, sortbylastname
, or custom binding takes in additional information , sets sort.
the second 1 this:
<span class="sorting" data-bind="sortfunction: 'username'">user name</span> <span class="sorting" data-bind="sortfunction: 'firstname'"> first name</span> <span class="sorting" data-bind="sortfunction: 'lastname'}"> last name</span>
and custom binding sortfunction:
ko.bindinghandlers.sortfunction = { update: function(element, valueaccessor, allbindingsaccessor, viewmodel) { var sortby = ko.utils.unwrapobservable(valueaccessor()); var items = viewmodel.items; $(element).unbind('click.sort').bind('click.sort', function() { items.sort(function(a, b) { return a[sortby]() < b[sortby]() ? -1 : 1; }); }); } }
another option mentioned joeseph pass property name click function, return function. don't think nice option custom binding, here's fiddle that:
<span class="sorting" data-bind="click: getsortfunction('username')">user name</span> <span class="sorting" data-bind="click: getsortfunction('firstname')"> first name</span> <span class="sorting" data-bind="click: getsortfunction('lastname')}"> last name</span>
and viewmodel change add function:
var listui = function listuif(items) { var self = this; self.items = ko.observablearray(items); self.getsortfunction = function(prop) { return function() { self.items.sort(function(a, b) { return a[prop]() < b[prop]() ? -1 : 1; }); }; }; return self; }
Comments
Post a Comment