This is my code with KnockoutJS:
var viewModel = function () {
var self = this;
self.items = ko.observableArray([
{ name: "Item 1", value: 1 },
{ name: "Item 2", value: 2 },
{ name: "Item 3", value: 3 },
]);
self.addItem = function () {
self.items.push({ name: "New Item", value: self.items().length + 1 });
};
self.removeItem = function (item) {
self.items.remove(item);
};
self.sortItems = function () {
self.items.sort(function (a, b) {
return b.value - a.value;
});
};
self.reverseItems = function () {
self.items.reverse();
};
};
ko.applyBindings(new viewModel());
I want to make sort and reverse method for arrays in knockoutJS, and that i make those but they are not working and that i dont recognise why there aren’t operating!!!
3
Answers
The bug in this example is that if you try to sort or reverse the items array, the data-bindings in the HTML will not update to reflect the new order of the items.
This is because the sortItems() and reverseItems() functions do not call the valueHasMutated() method on the items observableArray after changes have been made.
To fix this bug, you can add self.items.valueHasMutated(); at the end of both the sortItems() and reverseItems() functions.
I don’t think the accepted answer is correct. Both
sort
andreverse
are built-in and do not require you to callvalueHasMutated
in order to work, as you can see here. There must be some other issue with your code we’re not seeing.The problem is that the
sortItems
method has an incorrect comparison, you need to swapa
andb
. See: https://jsfiddle.net/martlark/z85hte9j/5/It should be: