What is the difference between the '[]' property and the '@each' property in ember.js?

房东的猫 提交于 2019-12-20 10:27:12

问题


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


回答1:


Use @each if you need to observe properties of array elements

@each supports observing properties of the elements inside the array. For example, people.@each.name. 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.



来源:https://stackoverflow.com/questions/16321885/what-is-the-difference-between-the-property-and-the-each-property-in-emb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!