Ember: Accessing child component functions in parent

Kshitij Srivastava
Code Abbot
Published in
2 min readOct 21, 2018
Sometimes one must do sneaky things to get other important things right — Sneaky Person

Frameworks make life a lot easier but there comes a day in every developer’s life when he realises that he has been caught up in what I like to call The Framework Trap.

Relatable?

Let me explain this to you with an example — I recently came across a project requirement that needed me to to ditch the DDAU (Data Down Actions Up) rule of Ember (déjà vu?). Such conflicting cases can arise in Ember due to scenarios like communications involved between sibling components, asynchronous data loading in separate components, use of third party libraries, etc. I usually try to do things in as much Ember(y) way possible but let’s just say in this particular scenario I was caught up in an intricate merger of the above mentioned scenarios. So, I figured a sneaky little solution to solve this problem utilising Ember’s DDAU rule itself by slightly misusing it.

To cut it all short, here’s the problem statement followed by the solution:

Call child component action / function from parent component

Solution

Now, we cannot do a sendAction from the parent component down to the child component due to Ember’s restrictions, but what we can do is send one from the child component to register a reference to itself with the parent (see where this is heading?). The parent can then use this reference to the child component to call its function whenever required. I decided to place the sendAction call inside didInsertElement hook of the child element to register itself with the parent component as soon as it is added to the parent DOM.

Following is the gist to the solution. You can also play around with the related Ember twiddle.

Thanks for reading through. If you liked the post, don’t shy off :) You can sneak in your support through claps. If you’re expecting more, go hit the follow button.

Cheers.

--

--

Kshitij Srivastava
Code Abbot

A science and tech enthusiast with a knack for art and love for books.