Which is corresponding event in Lightning Component? vs load or DOMContentLoaded within document

In init and afterRender of component, I attached handler to DOMContentLoaded and load like below, but seems never executed.

document.addEventListener('DOMContentLoaded', function () {
    console.log("@@@ DOMContent is Loaded. The text never shows up.");
    document.scroller = new Scroller('#wrapper', scrollerConfig);
});

Answer

Neither…

You want to use a the renderer JS instead and implement an afterRender function.

Any activity you need to do after the DOM has been constructed by the Lightning Components you should put there.

For instance, I was playing with a component that was using html canvas to present a donut chart.

To do this you need to get the canvas then the context so you can begin to draw. So I wrote a JS function in my helper like this:

doChart: function(component){

    //get handle to canvas and context
    var canvas = component.find('chart').getElement();
    this.ctx = canvas.getContext('2d');

    //...setup canvas params, size, BG, etc...

    //call an init function that draws my chart
    this.init();

},

Initially I was calling doChart from init…but I was getting undefined on the canvas instance…it hadn’t been rendered.

It’s important to realize that LCF doesn’t actually pass through any raw HTML. Everything is client composed.

The renderer is designed to be able to work with the base DOM drawn by the core component markup. So anytime you want to do DOM manipulation, or interact with elements in the DOM drawn by the component this is where you want to put you code. To get this working in my component, I simply invoke the doChart function from a renderer function. That function looks like this.

afterRender: function(component, helper) {
    this.superAfterRender();
    helper.doChart(component);
}

First call is the call to the super-component renderer. Always important as every component is a sub component of another.

Second line is to call helper.doChart and pass in the component.

I spent the better part of half a day pulling hair out, and trying to use standard HTML event handlers. Once I was pointed to this, everything snapped into shape immediately.

The full code from this component is available on github if you want to see it.

Attribution
Source : Link , Question Author : Leo , Answer Author : pchittum

Leave a Comment