Aditya Kappagantula
Aditya Kappagantula

Reputation: 562

Ember Array observer not working

export default Ember.Object.extend({
    myArray: Ember.A([null,null,null]),
    someFunction: function () {
         console.log('i am triggered');
         myArray[1] = 3;
    }.on('init'),
    hasValue: Ember.observer('myArray.[]', function () {
         console.log('i am changed');
    })
})

What is the mistake here? The observer function never gets triggered though someFunction is always reached.

Upvotes: 3

Views: 1305

Answers (2)

user663031
user663031

Reputation:

Use MutableArray#replace:

 this.get('myArray').replace(1, 1, [3]);

This means: starting at index 1, replace 1 element, with a 3. This triggers all the necessary dependencies and observers defined as myArray.[].

I'm surprised that your code does not spit out a ReferenceError, since you are referring to an undeclared variable myArray inside someFunction.

There's a convenience function for this that I can't put my finger on at the moment. Also, be aware that observers may not fire during initialization.

Upvotes: 3

jonnii
jonnii

Reputation: 28312

Using myArray.[] will only notify you when items are added or removed from the array. The correct way to do this is to use [email protected] which will observe all changes on the key property for each item in the array.

If I'm being honest, I actually don't know how to observe an array of primitives for changes (except for added/removed changes), so would probably do something like:

myArray: Ember.A([Ember.Object.create(), Ember.Object.create(), Ember.Object.create()]);

myArray[1].set('id', 3);

And then observe [email protected]. If you want to project those ids you could use mapBy:

ids: Ember.computed.mapBy('myArray', 'id')

I hope this helps!

Upvotes: 2

Related Questions