multiple sorting in backbone.js -
sorting in backbone it's working fine. want sort multiple fields, passing sort argument dynamically clicking sorting headers. have 5 headers(id,desc,type,category,hierarchy). when click headers it's sort ascending , next click descending problem sort 1 attribute want multiple attribute pass collection , maintain previous sorting order , again sort till data relative.
in collection:
sortasc: function(sortfield) { var key = sortfield; this.comparator = function(model) { return model.get(key); }; this.sort(); }, sortdesc: function(sortfield) { var key = sortfield; this.comparator = function(a, b) { = a.get(key); b = b.get(key); return < b ? 1 : > b ? -1 : 0; } this.sort(); },
view: called when click header(click event) , elem id (dynamically change on click) id,,desc,category,type , hierarchy.
sortitems: function(e) { if ( currentclass.indexof("ascending")>0 ) { this.currentcollection.sortasc(elem.id); } else { this.currentcollection.sortdesc(elem.id); } },
i create function receives comparators array , return composite comparator comparators[n] tie breaker of comparator[n-1]
var createcompositecomparators = function(comparators){ return function(a,b){ var = 0; var tempresult = 0; for(i=0; i<comparators.length; i++){ tempresult = comparators[i](a,b); if (tempresult !== 0 ) return tempresult; } return tempresult; }; };
and function creates comparator field, should accept [+|-]fieldname
(e.g. +count or -count)
var createfieldcomparator = function(fullfield){ var field = fullfield.substring(1); var desc = fullfield.substring(0,1) === "-" ? -1 : 1; return function(a, b) { return desc * (a.get(field) - b.get(field)); }; }
to finalize sortbyfields:
sortbyfields: function(sortfields){ // array var comparators = _.map(sortfields, createfieldcomparator);//create list of comparators list of fields in form of [+|-]field this.comparator = createcompositecomparators(comparators); this.sort(); }
to use send array of fields
collection.sortbyfields(["+category", "-id"]);
off course code not production ready... not tested
Comments
Post a Comment