connectedCallback()

This interface/callback gets invoked every time a copy of a Web Component gets added to the DOM. This is very useful when it comes to initializing events associated with the DOM inside the component, or state management (see Chapter 5, Managing States and Props), or anything that needs any sort of initialization or pre-checks.

Let's take a look at an example. In Chapter 1, Web Components Essentials and Specifications, we talked about a <student-attendance-table> component, where the Web Component makes a fetch call to the file student.json, in order to retrieve the attendance data and then display that data in the form of a table.

The correct way to write that Web Component would be to add a connectedCallback() method to the definition of the StudentAttendenceTable class and then make the fetch call inside this callback. 

This is what our code would look like:

// StudentAttendanceTable.js

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

this.innerText = this.getLoadingText();
}

connectedCallback() {
// let's start our fetch call
this.getStudentList();
}

getStudentList() {
// lets use fetch api
// https://developer.mozilla.org/en-US/docs/Web
// /API/Fetch_API/Using_Fetch
fetch('./student.json')
.then(response => {

// converts response to json
return response.json();

})
.then(jsonData => {
this.generateTable(jsonData);
})
.catch(e => {

// lets set the error message for
// the user
this.innerText = this.getErrorText();

// lets print out the error
// message for the devs
console.log(e);
});

}

generateTable(names) {
// lets loop through names
// with the help of map
let rows = names.map((data, index) => {
return this.getTableRow(index, data.name);
});

// creating the table
let table = document.createElement('table');
table.innerHTML = rows.join('');

// setting the table as html for this component
this.appendHTMLToShadowDOM(table);
}

getTableRow(index, name) {
let tableRow = `<tr>
<td>${index + 1}</td>
<td>${name}</td>
<td>
<input type="checkbox" name="${index}-attendance"/>
</td>
</tr>`;

return tableRow;
}

appendHTMLToShadowDOM(html) {
// clearing out old html
this.innerHTML = '';

let shadowRoot = this.attachShadow({mode: 'open'});

// add a text node
shadowRoot.append(html);
}

getLoadingText() {
return `loading..`;
}

getErrorText() {
return `unable to retrieve student list.`;
}
}

As you can see in the code, we are now making a call to fetch the student list inside the connectedCallback() method. This makes sure that the code gets executed, once the Web Component is attached to the web page.

Another example of a place where using the connectedCallback is helpful is event handling. Let's say we have a Web Component that shows a custom button. And the purpose of this button is to show some text right next to it stating the number of times the button was clicked. If we try to use it without connectedCallback, it would look something like this:

// 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', (e) => {
this.handleClick(e);
});
}

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

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

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

The associated HTML would look like this:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>Connected Callback Example</title>

<!--
Notice how we use type="module"
-->
<script type="module">

/// importing the first custom element
import CustomButton from './CustomButton.js';

customElements.define('custom-button', CustomButton);
</script>

</head>
<body>

<custom-button></custom-button>

</body>
</html>

Notice how an event listener is bound to the DOM in the connectedCallback() method. We will be talking about event listeners in detail in the Chapter 5Managing States and Props, but for now; we can use the code as an example. The preceding code makes sure that we bind a click event to the button only after the DOM is available on the page. This prevents us from creating event-related bugs, which I am sure has happened to every one of us.

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

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