skip to Main Content

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


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

    Login or Signup to reply.
  2. I don’t think the accepted answer is correct. Both sort and reverse are built-in and do not require you to call valueHasMutated in order to work, as you can see here. There must be some other issue with your code we’re not seeing.

    Login or Signup to reply.
  3. The problem is that the sortItems method has an incorrect comparison, you need to swap a and b. See: https://jsfiddle.net/martlark/z85hte9j/5/

    It should be:

    self.sortItems = function () {
      self.items.sort(function (a, b) {
       return a.value - b.value;
     });
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search