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!!!
>Solution :
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.