6

Ember's v1.0.0-rc.3 documentation of Ember.Array says:

You can use the methods defined in this module to access and modify array contents in a KVO-friendly way. You can also be notified whenever the membership if [sic] an array changes by changing the syntax of the property to .observes('*myProperty.[]').

I tried to come up with a minimal example observing array changes, but couldn't make the observer fire. What does a working sample look like?

P.S. notice this gotcha.

1
  • 1
    can you setup a jsfiddle of your non working example? Commented Apr 29, 2013 at 2:00

1 Answer 1

9

Oh hey, there's my answer!

There's a couple of ways you can observe Em.A() properties. You have .observes('a.[]'), .observes('a.@each'), and .observes('a.length'). The concept is the same as any property in Ember though, you just have to directly manipulate the array and the observer should fire. Obviously using the set method is not going to work on an (Ember) array, so perhaps that is where you went wrong?

I have modified my old jsfiddle to account for an observable array (I updated everything to the latest versions too).

I think it's important to bear in mind that the Ember Array is not actually an array - it's an object with some custom functions and properties that implement your usual array javascript functions. So you can't do something like: Em.A() = [1,2,3], because the type of Em.A is an object, not an array.

Another useful note is that the ArrayControllers have a content of an Ember Array, meaning that you have to observe the array of the content, not the content itself (i.e. do not observe arraycontroller.content, but instead observe arraycontroller.content.[]).

This is why you have to observe the weird looking prop.[] property on an Ember Array, because the value of an Ember Array is not what you're expecting.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Deif for this great feedback and the insights... yes, I didn't get the sample working for some similar gotcha: I used (... sticking to your jsFiddle example) this.person.push(3) instead of this.person.pushObject(3). One needs to use the pushObject(..) method for having the observes(..) observers fire. I guess this is what the Ember documentation means with "KVO-compliant".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.