Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computed Properties and @each

I've been reading through the docs and API and I'm having a hard time finding an explanation for the following:

export default Ember.Controller.extend({
  collectionTotal: function() {
    var games = this.get('model');
    return games.length
  }.property('@each')
});

What is actually happening with the .property('@each')? I know I am getting the computed property back, I don't understand what @each is.

like image 808
Gregg Avatar asked Feb 17 '26 02:02

Gregg


1 Answers

What is @each?

@each observes individual properties on each item in an array.

For example, if I observe [email protected], I will receive an event if:

  • the users property is replaced e.g. this.set('users', ...)
  • an item is added or removed from users
  • the name property changes on any of the items

You can observe multiple properties using this syntax: users.@each.{name,email}

You cannot nest them. This will not work: [email protected][email protected]

Read more in the official documentation:

  • Computed Properties and Aggregate Data with @each
  • Ember.ArrayProxy Class

To answer your question

@each by itself doesn't make sense. You can observe the [] property if you only need to watch for items being added or removed.

Typically you should observe the same properties that are used in the body of the function. In your example that would be model and length:

  collectionTotal: function() {
    var games = this.get('model');
    return games.get('length');
  }.property('model.length')

Or equivalently:

  collectionTotal: function() {
    return this.get('model.length');
  }.property('model.length')

Or equivalently:

  collectionTotal: Ember.computed.reads('model.length')
like image 193
dwickern Avatar answered Feb 19 '26 14:02

dwickern



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!