1

I have a list with an observer function on it :

var names = ['joe', 'bob', 'loic'];

Object.observe(names, function(changes){
    changes.forEach(function(change) {        
      console.log(change.type, change.name)
    });
    console.log("names",names);
});   


console.log("######## del bob");
names.splice(1,1);// output is "update 1 - delete 2", why?
console.log("names", names) // but "bob" is the one deleted in the list

The deleted index according to the change object is 2, but I'm deleted the index 1, and the list has actually the index 1 deleted. Do you know why?

Is it because index 1 is updated to get index 2 value and index 2 is deleted? Is there a way to get the actual deleted element index?

Loic
  • 3,079
  • 4
  • 22
  • 38
  • 1
    Deleting an element does not mean that all the following elements are shifted down. If you did `delete names[1]` you would just get a single `delete` message, and the array would contain `['joe', undefined, 'loic']` – Barmar Nov 27 '14 at 17:11
  • 1
    Yep, it's because [how `.splice` works internally](https://es5.github.io/#x15.4.4.12). It will first overwrite (update) the elements of the array and then remove them. – Felix Kling Nov 27 '14 at 17:14
  • Thanks, using delete it works! :) (JS neewbie inside) – Loic Nov 27 '14 at 17:22
  • 1
    Maybe you could use Array.observe instead? – Xavier Delamotte Nov 27 '14 at 17:23
  • Well, `delete` leaves a hole in the array, which is usually not desired. – Felix Kling Nov 27 '14 at 23:10

1 Answers1

0

You can capture a splice event at the right index with Array.observe :

var names = ['joe', 'bob', 'loic'];

Array.observe(names, function(changes){
    changes.forEach(function(change) {        
      console.log(change.type, change.name);
    });
});   

Thanks @xavier-delamotte :)

Loic
  • 3,079
  • 4
  • 22
  • 38