Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ember's "observes(..)" to observe some array's modification

Tags:

ember.js

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.

like image 772
Abdull Avatar asked Apr 29 '13 00:04

Abdull


1 Answers

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.

like image 186
DF_ Avatar answered Sep 23 '22 09:09

DF_