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.
The MDN reference is not clear about what circumstances fire each change type. Here is a detailed explanation:
Covers every change that you would expect to happen in an array. All the following functions trigger it:
push()
pop()
shift()
unshift()
splice()
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()
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With