Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under what condition would Array.observe's "add" event trigger?

I'm learning about observing Array objects. I found the following surprising:

var fooArray = [];
Array.observe(fooArray, function(changes){
    console.log('changes:', changes[0].type);
});
fooArray.push({});

results in the type of change being splice and not add

What methods would result in a change event of type add? It would seem to me that pushing a single value on it would be the most likely scenario.

like image 701
Sean Anderson Avatar asked Mar 26 '15 00:03

Sean Anderson


1 Answers

The MDN reference is not clear about what circumstances fire each change type. Here is a detailed explanation:

splice

Covers every change that you would expect to happen in an array. All the following functions trigger it:

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()

update

Triggers if the value of some element changes:

var arr = ['a', 'b', 'c'];
Array.observe(arr, function (changes) {
    console.dir(changes);
});
arr[0] = 'A'; // triggers 'update'

It's worth mentioning that some array functions may also trigger it, like reverse().

add | delete

As unintuitive as it seems, these types are triggered when a property is added to/deleted from the array. For example:

var arr = ['a', 'b', 'c'];
Array.observe(arr, function (changes) {
    console.dir(changes);
});
arr.foo = 'bar'; // triggers 'add'
delete arr.foo;  // triggers 'delete'

P.S.: See Jack's answer on why it behaves like this.

like image 88
Lucio Paiva Avatar answered Oct 08 '22 08:10

Lucio Paiva