Polymer Component Lifecycle - How to call a function after the Local DOM ha

Hello all,

I’ve made a custom template that relies on a function call from the constructor to set up the component after the template has been added to the shadow dom. I’m trying to use some SVG and hence cannot use the ElementAPI methods thus wrapping SVG.js in a polymer element.

If I use getElement().callFunction(“example”) in the constructor the this.$ is undefined at that point of time.

How can I make the function call during component construction and still access the template DOM?

The way I get around it at the moment is to create a new Div rather than reference the template and then
in after my constructor function,

initFunctionCall(){

	this.newDiv = document.createElement("div");
	
	// use new div in a non Element API Class.

}

afterServerUpdate(){     	
    this.$.templateDiv.appendChild(this.newDiv);
}

Thanks heaps

p.s sorry about the “ha” in the heading. Not sure why that’s there.

Hayden

Hello Hayden,

in my case I had a similar problem to access a dom-repeat template that when the constructor was called, it was not attached yet.

I solved it by adding a dom-change event listener in the ready method of the component. So, when the template is initialized you can work with it.

Below it is the code:

<template is="dom-repeat" items="{{fragments}}" id="container" as="fragment">
  <distribution-fragment value="{{fragment.text}}" < distribution-fragment displayed-value="0"></distribution-fragment>
 </template>
  ready(){
      super.ready();
      let fragmentsTemplate = this.$.container;

      fragmentsTemplate.addEventListener('dom-change', function() {
        this._configureFragments();
      }.bind(this)); 
  }

ahh Thankyou very much. That’s a bit of a trick.

If I don’t include the super.ready() callback in my Polymer class, like so,

ready(){

}

Then any function call I make from Vaadin during component construction doesn’t have
this.$ defined in its context.

But if I provide the following,

ready(){
   super.ready();
}

Then I can access this.$ during function calls in the server Class Constructor.

I missed this in the Polymer Docs

https://www.polymer-project.org/3.0/docs/devguide/custom-elements#ready-callback

Thanks heaps.

You may find this more elegant.

In my code the dom-repeat was generating a number of paper-toggle-buttons which I needed to add listeners to.

If you add the following method to you polymer component class then it will be called after the dom-repeat elements have been rendered.

    afterServerUpdate()
        {
			let obj = this;
			// The call to querySelectorAll will now succeed.
            let elems = this.shadowRoot.querySelectorAll("paper-toggle-button");
        }