1

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

2
  • How do you know it's not working? Does anything happen? Have you verified that the functions are being called? Are errors reported? Commented Apr 7, 2023 at 13:26
  • I think the example at jsfiddle.net/martlark/z85hte9j/5 makes sense Commented Apr 12, 2023 at 10:49

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried this code and it worked.
4

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;
 });
};

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.