Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write Sort and Reverse function in Knockout.js?

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!!!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading