Adriano Spadoni
Adriano Spadoni

Reputation: 4800

Polymer 2.0: Event listeners where is the ideal place to add it?

I've seen people adding the event listener on the "ready" function and others on "connectedCallback". My question is, what are the pros and cons of each place? On connected we are responsible to remove it; in ready, it will stay there, and I'm unsure if it is a problem.

Should I do this:

connectedCallback() {
    super.connectedCallback();
    this.addEventListener('click', this.myFunction.bind(this));
}

disconnectedCallback() {
    super.disconnetedCallback();
    this.removeEventListener('click', this.myFunction);
}

Or this:

ready() {
    super.ready();
    this.addEventListener('click', this.myFunction.bind(this));
}

Upvotes: 2

Views: 623

Answers (1)

Schrodinger's cat
Schrodinger's cat

Reputation: 1102

Up until Polymer 1.x.whatever , the ready callback in the life cycle of an element, was called, once

  • the element registered its shadow DOM
  • any <content>'s were distributed

and then, post ready , attached was fired

So, you could possibly have used ready as a one time callback after everything was indeed ready

With Polymer 2.0 onwards, there have been contractual changes to how callbacks are fired, and

  • The ready callback no longer is guaranteed to execute after the new <slots> are distributed meaning, there is no surety that the ready itself will wait for content / light DOM distribution.

  • attached is now the new connectedCallback and is essentially useful for element level DOM manipulations such as setting attributes , appending children etc. This is a lifecycle change that happens after the slot nodes are distributed and the element itself is attached in the DOM hierarchy, but not necessarily after a paint.

SO, for any event that does not rely on any ::slotted content, use the ready callback

for anything that requires a knowledge of all distributed content along with the shadow DOM, use the connectedCallback

However, when possible, use the afterNextRender method of the super class Polymer , within your element's callback to add event listeners

these are what I could possibly think of.

All this and much more, if it helps, here

I haven't yet read about us having to remove an event listener from a lifecycle callback, or anything as such.

If you are referring to cases where, the element itself may be connected and disconnected dynamically / or in the flow of things,

And, with that in mind, you are adding an event listener on a global / native element within your element's life cycle callbacks ,

like attaching an event listener on the window inside your custom-element's ready or connectedCallback ,

Only in such cases, does polymer advise you to remove the event listener on disconnect

Upvotes: 4

Related Questions