Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I observe array changes and see which new element is added?

onArrayChanged: function(obj, keyName, value) {

    // What is value here, exactly?

}.property('array.@each')

When an element is added to the array, how do I know which value was added? LIkewise, when a value is removed from the array, how do I access that?

like image 621
Oliver Zheng Avatar asked Apr 30 '12 20:04

Oliver Zheng


People also ask

How do you watch changes in array?

To watch for array changes with JavaScript, we use the underscore-observe library.

How do you check if an element is already in an array?

The simplest and fastest way to check if an item is present in an array is by using the Array. indexOf() method. This method searches the array for the given item and returns its index. If no item is found, it returns -1.

How can I find and update values in an array of objects?

To update an object's property in an array of objects, use the map() method to iterate over the array. On each iteration, check if the current object is the one to be updated. If it is, modify the object and return the result, otherwise return the object as is. Copied!

How do you find a matching element in an array?

To find the first array element that matches a condition:Use the Array. find() method to iterate over the array. Check if each value matches the condition. The find method returns the first array element that satisfies the condition.

How do you check if an element in one array is in another array?

Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.

Which method is used to add new element to an array of objects?

The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array.


1 Answers

Have a look at addArrayObserver, see http://jsfiddle.net/pangratz666/EE65Z/:

var a = Ember.A('a b c d e f g'.w());

var o = Ember.Object.create({
    arrayWillChange: Ember.K,
    arrayDidChange: function(array, start, removeCount, addCount) {
        console.log(arguments);
    }
});

a.addArrayObserver(o);
like image 179
pangratz Avatar answered Oct 01 '22 02:10

pangratz