I learned this the hard way.
It was a simple enough task: I had two lists of items and I wanted to display the differences between them.
I figured that once I had the list of differences, I should be able to iterate through them in my template:
{{#each differences}}
<li>{{this}}</li>
{{/each}}
Figuring the template would be easy, I concentrated on writing good, testable code to calculate the differences. Once I had that, I sent it to my model in init():
init: function() {
this.set('differences', calculateDifferences(this.get('listOne'), this.get('listTwo'));
}
I thought I was done. I went to the template and saw--- nothing.
I went in to full debugging mode.
Logging the differences in init()
showed all of the differences I expected. Logging differences
after set()
gave the expected results as well.
I figured it was a problem with my loop. I changed it over from an {{#each differences}}
to a {{#each differences as |difference|}}
. No dice. I tried writing my own loop helper. Still nothing worked.
I had been searching StackOverflow this whole time but no one else seemed to be having this problem. That’s never a good sign.
What worked was reaching out to my coworkers. Most of my code was fine, but Jerry took one look at my init()
function and said, “You should call this._super()
Some of us wondered if that was a best practice or absolutely necessary. Computers make answering that kind of question easy. I added this._super(...arguments)
to my init()
call and hit refresh.
Just like that, my list items showed up.
I was right in that the differences were being calculated. The problem was that this component was a subclass of something that had more work to do in init()
. Mixins call this._super()
in the order you include them, and the superclass gets invoked last. It can be easy to forget whether or not a hook's super is doing some work and it's easy to get lost like I did. Chris wrote a twiddle which demonstrates the call order.
Best practices are those for a reason. So always call this._super()
when overriding any of the lifecycle hooks.
Have a question about Ember or a tip to share? Email us at hello@mutuallyhuman.com and it might be featured here.
Also be sure to follow us for the rest of our Summer of Ember series.