8

I have a scenario in emberjs component where the observe does not get hit. I figured out the reason as "the component is not yet inserted when the component property being observed is set."

My questions is, couldn this be handled in a better way in ember js?

Better explanation can be found in the below jsbin`s.

Not working Scenario

Working scenario

wallop
  • 2,510
  • 1
  • 22
  • 39
  • What exactly are you trying to accomplish here? In this scenario, both observer functions would be better served as a computed property (via `Ember.Computed`). – awgreenarrow08 Jan 06 '15 at 18:45
  • Agreed, observers are overkill in both situations – Kingpin2k Jan 06 '15 at 22:19
  • Like i have mentioned in the comments, this was an example and not the actual use case. The actual use case being a huge one i thought of simplyfying it. Basically there is a lot of calculation in the observer and its not just assigning it to another property Also when you say " both observer functions would be better served as a computed property " if you use computed property in component it wont work owing to the same reason why the observer is not working – wallop Jan 07 '15 at 01:35
  • The question you need to ask yourself is, why am I computing something, that isn't going to be used. If it's going to be used, why am I not using a computed property? – Kingpin2k Jan 07 '15 at 02:23
  • @Kingpin2k may be i didn get your point the right way but i feel i didn explain well either. The example stated is just an example and not the actual use case i am ending up with! I am computing something that is being used but i am computing more than one. Since i am computing more than one i felt its better to use observers than computed properties! – wallop Jan 07 '15 at 05:59

1 Answers1

15

You can specify .on('init') to force the observers to run right after initialization; otherwise like @Kingpin2k mentioned - they don't run

App.TextboxDisplayComponent = Ember.Component.extend({
  displayText: '',        

  boundProperty: '',

  observeBoundProperty: function () {
    this.set('displayText', this.get('boundProperty'));        
  }.observes('boundProperty').on('init')
});

Your (non-)working example here

Kalman
  • 8,001
  • 1
  • 27
  • 45
  • 1
    exactly what i wanted thank you When i tried this i thought the observer will get hit only "on('init')" and wont get hit when the usual changes happens. Now i tested it and it happens even when there is a change – wallop Jan 07 '15 at 01:28
  • However i just realised why i didn use this concept earlier as well, there is a catch with this! observeBoundProperty would get exectued on init even if boundProperty is not changed. If i wanted observer to get hit only on change then it wont be of much help : ) But nevertheless i could have a condition check inside it and most importantly its a much more cleaner version! – wallop Jan 07 '15 at 01:40