shanky
shanky

Reputation: 7263

afterRender vs didInsertElement

Whats the difference between the following 2 things in ember.js?

Is there a rule of thumb for when one is preferred over the other ?

1) afterRender run loop

2) didInsertElement hook

Upvotes: 1

Views: 2057

Answers (2)

Ember Freak
Ember Freak

Reputation: 12872

I always prefer didInsertElment hook, if something I have to deal with rendered DOM element. Whenever you thought of using afterRender run loop hack, to solve your problem, then that's the right time to introduce component.

There is no hook in route, to know all the UI element is rendered in DOM, like component has didInsertElement and didRender hook.

The mostly afterRender run loop hack will be used in route file , to run some logic after all UI rendering completed.

You can also use component hooks at the route level video from Ember Map. https://embermap.com/video/component-hooks-at-the-route-level

Upvotes: 2

malchv
malchv

Reputation: 21

afterRender gives you a way to schedule some logic to be executed after all previously scheduled render tasks are complete. Taken from Ember Run Loop docs.

$('a').click(() => {
  // Do something.. 
  Ember.run.schedule('afterRender', () => {
    // Do yet more things
  });
});

didInsertElement is a component hook that will be called only one time (unlike didReceiveAttrs) and gives the developer an option to add additional logic.
Since it is only triggered once when the component element is first rendered it is a good place to attach event listeners. More info in Ember Component Lifecycle docs.

You can get some more info from Ember.run.schedule section here. You can see how the hook and afterRender can be used together to avoid UI issues.

Upvotes: 2

Related Questions