Taztingo
Taztingo

Reputation: 1945

Ember Computed Property vs Ember Observer

None of the previous questions that I saw on here seemed to cover the topic of when to use an Ember Computed Property vs an Ember Observer. I understand that a Computed Property uses previous attributes to help generate a new attribute and is updated in the run loop.

Person = Ember.Object.extend({
  // these will be supplied by `create`
  firstName: null,
  lastName: null,

  fullName: Ember.computed('firstName', 'lastName', function() {
    return `${this.get('firstName')} ${this.get('lastName')}`;
  })
});

An observer on the other hand is updated outside of the run loop, and can watch anything even a Computed Property. It reacts to any type of change.

Person = Ember.Object.extend({
  // these will be supplied by `create`
  firstName: null,
  lastName: null,

  fullName: Ember.computed('firstName', 'lastName', function() {
    return `${this.get('firstName')} ${this.get('lastName')}`;
  }),

  fullNameChanged: Ember.observer('fullName', function() {
    // deal with the change
    console.log(`fullName changed to: ${this.get('fullName')}`);
  })
});

The Ember documentation then states that observers are typically over used. Can someone give a better example of the correct usage of observers? What else can they watch, and what are the effects of incorrect usage vs correct usage?

Source code can be found on ember documentation: https://guides.emberjs.com/v2.3.0/object-model/observers/

Upvotes: 7

Views: 4352

Answers (1)

user663031
user663031

Reputation:

Computed Property uses previous attributes to help generate a new attribute and is updated in the run loop

Yes, but lazily--meaning only when referenced, and their dependencies changing has invalidated the cached value.

The Ember documentation then states that observers are typically over used.

Yes, Observers fire synchronously whenever the watched property changes, even if the reason is to recompute something that won't be used. Using observers for what should be computed properties is one of the classic Ember anti-patterns.

I checked a couple of large applications I worked on and found observers being used for things like calling some third-party library as necessary when something changed, or changing the app's language when a new UI language was chosen.

Upvotes: 6

Related Questions