Object.observe does not always gives me the right deleted index on an Array

108 views Asked by At

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?

1

There are 1 answers

0
Loic On

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 :)