binding: Adding and then sorting an array breaks repeat binding

When adding (pushing) to an array and then sorting the result, a repeat binding doesn’t update correctly.

I have created a repro here. I have added a repeat binding over a collection to the Welcome view model. There are a couple buttons below, one to add then sort and one to add without sort. If you use add with sort, you will see the unexpected behavior.

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 23 (17 by maintainers)

Commits related to this issue

Most upvoted comments

I’m coming across a similar issue and can’t get it to work. In an array (this.steps): I need to move an item from a position to another (index previousPosition to newPosition). This array is used in a repeater in the view.

Here are the relevant parts of the code I’ve tried:

steps.js (VM)

// Option 1 (using splice)
this.steps.splice(newPosition, 0, this.steps.splice(previousPosition, 1)[0]);

// Option 2 (using sort)
let index = 0;
for(let step of this.steps) {
  step.position = (index < newPosition) ? index : index+1;
  if(index == previousPosition) {
    step.position = newPosition;
  }
  index++;
}
this.steps.sort((a,b)=>{
  return a.position - b.position
});

steps.html

<li repeat.for="step of steps">...</li>

Both options have problems when the view gets updated. Sometime the moved item gets duplicated, sometimes the array gets an empty new item, sometimes an item gets missing, …

Is this stil a bug in the binding system or am I doing something wrong when updating the array ?