How to manipulate an Ember Object and only notify propagate changes when all modifications have been done

In my actual scenario I am trying to move one Array element to another position in the Array.

To do so I remove the element from the old position and add it to the new position:

this.get('myArray').removeObject(element);
this.get('myArray').insertAt(newIndex, element);

The problem is that when the removeObject change propagates to the rest of my code a lot of side effects are happening because the missing element.

I would like to make both manipulations at once and notify the changes after the modifications have been finished.

PS: please don’t get attach to the actual example, I am not looking for workarounds for this case but a general solution for element manipulations in a batch.

this.beginPropertyChanges();
this.get('myArray').removeObject(element);
this.get('myArray').insertAt(newIndex, element);
this.endPropertyChanges();

This is most definitely a private method…so…use at your own risk.

The other option could be to create a copy of the array, manipulate that array, and replace it after the last step.

let myArray = this.get('myArray').slice(0);
myArray.removeObject(element);
myArray.insertAt(newIndex, element);
this.set('myArray', myArray);
1 Like

This works as a charm :ok_hand:

The option of using private methods scaries me :head_bandage:

1 Like