Is it possible for a view to observe a parent's property?


#1

Hello,

I have a component with a few sub-views and I would like that one of those views to be able to observe one of its parent’s properties. Is that possible? and if not, how can I achieve it?

I’m able of showing in the console the info of that property by typing ‘controller.propertyX’ but when I try to observe it does nothing.


#2

It seems that ‘parentView.parentView…parentView.propertyX’ does the job but it doesn’t seem very elegant :confused:


#3

Hmm, it seems like a contradiction to the ‘data down, actions up’ principle.

Would it not be possible for the parent to send a message to the component if something changes?


#4

How can I send a message from the parent?


#5

This kind of pattern, given a parentFoo you want to bind. This way it is passed down to the bottom component. Hope this makes sense.

{{top-component parentFoo=parentFoo}}

Then

//middle-component.hbs
<div>
  {{middle-component parentFoo=parentFoo}}
</div>

Then

//bottom-component.hbs
<div>
  {{bottom-component parentFoo=parentFoo}}
</div>

In bottom-component you should have access to parentFoo e.g.

//bottom-component.js
import Ember from 'ember';

export default Ember.Component.extend({
  someFunction: function() {
    var pFoo = this.get('parentFoo');
    // do something interesting with it!
  }
});

Basically you’re just passing the property into the bottom component explicitly, rather than the bottom component asking its parent for the property of its parent!


#6

So it needs to go through each element between the parent and the desired child. Isn’t it adding a lot of unnecessary properties to the intermediate children?

By the way, thank you very much for your example :smile:


#7

It’s just one possible way of doing it.

There are many others, but this seemed reasonable based on the description you gave. Without a bit more context and / or code sample, it’s difficult to offer alternatives.

One other possible way would be to use block syntax http://www.slideshare.net/mixonic/new-component-patterns-in-emberjs, the first section of these slides may help.