I had a sorted list using knockout.js for a select list. I want to convert it for an unordered list. What is the method for sorting a list with knockout.js? I am thinking the error is with: allItems().length > 1
/
var BetterListModel = function () {
this.allItems = ko.observableArray([
{ name: 'Denise' },
{ name: 'Charles' },
{ name: 'Bert' }
]); // Initial items
this.sortItems = function() {
this.allItems.sort();
};
};
ko.applyBindings(new BetterListModel());
<button data-bind="click: sortItems, enable: allItems().length > 1">Sort</button>
I had a sorted list using knockout.js for a select list. I want to convert it for an unordered list. What is the method for sorting a list with knockout.js? I am thinking the error is with: allItems().length > 1
http://jsfiddle/infatti/Ky5DK/
var BetterListModel = function () {
this.allItems = ko.observableArray([
{ name: 'Denise' },
{ name: 'Charles' },
{ name: 'Bert' }
]); // Initial items
this.sortItems = function() {
this.allItems.sort();
};
};
ko.applyBindings(new BetterListModel());
<button data-bind="click: sortItems, enable: allItems().length > 1">Sort</button>
Share
Improve this question
asked May 24, 2013 at 21:43
simplesimple
2,3977 gold badges36 silver badges55 bronze badges
2 Answers
Reset to default 8var BetterListModel = function () {
this.allItems = ko.observableArray([
{ name: 'Denise' },
{ name: 'Charles' },
{ name: 'Bert' }
]); // Initial items
this.sortItemsAscending = function() {
this.allItems(this.allItems().sort(function(a, b) { return a.name > b.name;}));
};
this.sortItemsDescending = function() {
this.allItems(this.allItems().sort(function(a, b) { return a.name < b.name;}));
};
};
lines explained: weWiliChangeTheArrayToValue(weWilSortTheArrayWithASpecialFunction(ComparatorFunction))
ComparatorFunction ie.
function(a, b) { return a.name < b.name;}
is a special function that helps the sort function to... well sort.
It takes 2 arguments and pares them returning true if first argument is 'bigger' (should be further away on the list) and false if the first argument is 'smaller'
Every (almost) sorting algorithm works by paring 2 elements of sorted collection until all are in order.
Changing the order is done by making sure that the function returns false when it would return true normally - easiest way to do so is by changing the > operation to <
EDIT one more thing: if you pare non-ASCII characters use return a.localCompare(b); (and return b.localCompare(a);) and when dealing with numbers use "-" sing so it's an arithmetic operation
EDIT2
Warning the above method ">" might break with duplicates in array use
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
instead (or just localCompare)
this.allItems(this.allItems().sort(function(a, b) { return a.name > b.name;}));