lundi 8 août 2016

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: http://ift.tt/2aUVQEl




Aucun commentaire:

Enregistrer un commentaire