I've noticed that the enumerable mixin has computed properties that depends on the '[]'
property, while ember arrays also have the '@each'
property.
What is the difference between depending on '[]'
and '@each'
?
My vague understanding (correct me if I'm wrong) is that '[]'
is triggered when the array content is replaced. But is this different than depending on the property itself?
Consider the the following class:
C = Ember.Object.extend({
things: null,
watcher1: (function() {
console.log('watcher1')
}).observes('things.[]'),
watcher2: (function() {
console.log('watcher2')
}).observes('things.@each')
});
And I create an instance as follows:
c = C.create({things: Ember.A(['a', 'b'])});
The following:
c.get('things').replace(0, 1, ['z'])
triggers watcher1
and watcher2
And the following:
c.get('things').setObjects(['1', '2'])
also triggers watcher1
and watcher2
As does:
c.get('things').addObject('v')
So is there any difference? When should we use one vs. the other?
Thanks! Kevin
Tracked properties replace computed properties. Unlike computed properties, which require you to annotate every getter with the values it depends on, tracked properties only require you to annotate the values that are trackable, that is values that: Change over the lifetime of their owner (such as a component) and.
What are Computed Properties? In a nutshell, computed properties let you declare functions as properties. You create one by defining a computed property as a function, which Ember will automatically call when you ask for the property. You can then use it the same way you would any normal, static property.
Use @each
if you need to observe properties of array elements
@each
supports observing properties of the elements inside the array. For example, [email protected]
. The bracket notation does not support this. Here is a jsbin demo.
@each
is a property of Array instances that returns an EachProxy
instance that handles the delegation. On the other hand, []
simply returns this
.
Use []
if you need it to work on non-Array enumerables
According to the ember changelog, the bracket notation was made defunct in favor of @each
in ember 0.9.4, but then re-enabled in 0.9.8. The commit that re-enables it indicates that []
can be used for non-Array enumerables such as Ember.Set
instances. jsbin demo.
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