Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember.observer run on init

I'm attempting to build an Ember app without prototype extensions and the Ember docs give examples of how to do this, but they don't include the example of when I want my observer to run on init. So currently if my code were written like this:

fullNameChanged: function() {
   // deal with the change
}.observes('fullName').on('init')

The only example I can find to write it is like this:

Person.reopen({
  fullNameChanged: Ember.observer('fullName', function() {
    // deal with the change
  })
});

So how would I tell this code to run on init?

like image 622
Taylor Hobbs Avatar asked Apr 11 '15 15:04

Taylor Hobbs


1 Answers

May be you are looking for this

Person.reopen({
    fullNameChanged: Ember.on('init', Ember.observer('fullName', function () {
        // deal with the change
    }))
});

OR (this won't fire handler if change happens on init, use above on that case)

Person.reopen({
  init: function(){
    Ember.observer('fullName', function() {
      // deal with the change
    });
  }
});

Alright, this edit for answer the mistakes(?) mentioned below

  1. Well, sometimes it might be necessary to fire the observer on initialization time.

  2. Ember.observer is an Ember namespace method, not part of Ember.Object's prototype. Therefore this.observer never exists, but addObserver() does.

  3. There is no need to invoke the handler, Ember runtime will invoke the handler when the property changes

  4. calling this._super is unnecessary unless it really does matter. In this case, if Person just extends Ember.Object calling super doesn't do anything.

    By default, does nothing unless it is overridden during class definition.

  5. It's contextual, and as long as OP didn't specify anything about class definition it's beyond the scope of answering.

Nothing better explains than an example

like image 114
code-jaff Avatar answered Oct 11 '22 23:10

code-jaff