Reputation: 23
I'm struggling to fully grasp the component lifecycle. I've created a component, but I need my custom javascript function to run after the DOM is complete. I've scoured through the EmberJS Docs and Stackoverflow, but any documentation I come across doesn't work as I intended.
My Issue
I've attempted to use didInsertElement
and didRender
, but they still get called before my repeating elements have loaded in the DOM. How do I circumvent this to have my Javascript run after the DOM has fully rendered.
My Attempts
Below is an extremely stripped down and barebones example using an alert
in place of my script. The desired outcome is to have this alert
appear after the DOM is rendered, the below examples have it alert before.
import Component from '@ember/component';
export default Component.extend({
didRender() {
alert('didRender');
},
didInsertElement() {
alert('didInsertElement');
}
});
Thanks in advance.
Upvotes: 2
Views: 824
Reputation: 166
Although creating a child component is always safe, ( as said in ember's docs
When a view has children, didInsertElement will be called on the child view(s) first and on itself afterwards.
)
, however, even without child components, the didInsertElement hook will trigger only after the component is inserted to DOM. Here is an example twiddle.
Upvotes: 0
Reputation: 65183
Assuming you have the following template
{{#each this.items as |item|}}
<ItemComponent @item={{item}} />
{{/each}}
You want to know when the the list is done rendering?
extract the above template into a component.
<ItemList @items={{this.items}} />
where ItemList
is defined as
import Component from '@ember/component';
export default class ItemList extends {
didInsertElement() {
console.log('list was inserted');
}
}
Here is the code:
If you open the console, you'll see:
item 1 was inserted
item 2 was inserted
item 3 was inserted
item 4 was inserted
item 5 was inserted
list was inserted
Upvotes: 1