Search code examples
ember.jsobservers

Ember observer not working on nested property


I have created a mock application to illustrate the situation I am facing: Mock App

In this application; I have created a service with a single boolean property and a function to toggle that property (x); and two components (one to toggle the service's property; the other to observe the number of toggles and display it). The observer lies in toggle-observer. It is added directly to service's property as: myService.x. The code is not working as is; however if the comment at line 14 of toggle-observer.js is commented out; the observer starts working.

My question is that, do I need to perform a get to the whole path of a nested observer property to get it working? Is this the expected behavior? If so, can somebody explain why? My best regards.

Note: This is a mock example to illustrate the case; it is not related to anything I am designing in a real app. I am trying to avoid observers as much as possible; but I ran into this situation while trying out sth. and decided to ask it.


Solution

  • From ember guide service

    Injected properties are lazy loaded; meaning the service will not be instantiated until the property is explicitly called. Therefore you need to access services in your component using the get function otherwise you might get an undefined.

    From ember guide, unconsumed computed properties do not trigger observers. By combining the above two concepts, we can come to the below conclusion,

    You haven't used myService any of the property inside toggle-observer component so it will be undefined until you explicitly call get function or use it in template.

    Unless you use it x property in toggle-observer component, then it will not trigger observer. You need to consume it either in toggle-observer.hbs file or in init method.