disconnectedCallback()

Just like there are certain operations that need to be performed when a Web Component is added to the DOM, there are certain operations that need to be performed after the component is removed from the DOM. The most common example of this scenario is, again, event handlers. Event handlers consume memory, and, when the DOM associated with them is removed, the event handler is still on the page, listening to events, still consuming memory. The callback, disconnectedCallback(), gives Web Components a way to write code that can handle these scenarios. 

Let's take a look at the <custom-button> element and how we can use disconnectedCallback() to remove the attached event:

// CustomButton.js

export default class CustomButton extends HTMLElement {
constructor() {
super();

// Initializing an initial state
this.timesClicked = 0;

let template = `
<button>Click Me</button>
<span>${this.getTimesClicked()}</span>
`;

this.innerHTML = template;
}

connectedCallback() {

// adding event handler to the button
this.querySelector('button')
.addEventListener('click', this.handleClick.bind(this));
}

disconnectedCallback() {
console.log('We are inside disconnectedCallback');

// adding event handler to the button
this.querySelector('button')
.removeEventListener('click', this.handleClick);
}

handleClick() {
// updating the state
this.timesClicked++;

this.querySelector('span')
.innerText = this.getTimesClicked();
}

getTimesClicked() {
return `Times Clicked: ${this.timesClicked}`;
}
}

If you look at the disconnectedCallback() method, we have a console.log statement and the code to remove the event. When you are running this Web Component on a page, you can manually remove the component and see that disconnectedCallback() gets called automatically. I prefer going to the dev console and typing the following code to see it happen:

document.querySelector('custom-button').remove();

This will remove the first instance of <custom-button> from the page, thus triggering the disconnectedCallback() method.

Removing an event handler is only one of the uses. There can be any number of use cases that need to be performed before removing the Web Component from the DOM.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.219.65