-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom-lifecycle-methods.html
67 lines (58 loc) · 2.19 KB
/
custom-lifecycle-methods.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="shortcut icon" href="./webcomponents.png">
<title>Trying WebComponents</title>
<script src="vendor/document-register-element.js"></script>
<script>
class MyElement extends HTMLElement {
constructor() {
super();
console.log('Custom Element is constructed');
}
// life cycle callback methods
connectedCallback() {
console.log('Custom element is being added to the DOM');
}
disconnectedCallback() {
console.log('Custom elment is being removed from the DOM');
}
// we can also listen to attribute changes onour elment
// first we have to get the attribute we want to listen for
static get observedAttributes() {
return ['demo'];
}
attributeChangedCallback(name, oldValue, newValue) {
console.log('Attribute changed', name, oldValue, newValue);
}
}
// tell the browser about the custom element
window.customElements.define('custom-element', MyElement);
</script>
</head>
<body>
<script>
//to see all the lifecycle callbacks in action we neeed to create it dynamically
let $element = document.createElement('custom-element');
setTimeout(() => {
// adding element to the DOM
document.body.appendChild($element);
}, 2000);
setTimeout(() => {
// modify the 'demo' attribnute
document.querySelector('custom-element').setAttribute('demo', '123');
}, 4000);
setTimeout(() => {
// change value of the 'demo' attribnute
document.querySelector('custom-element').setAttribute('demo', '1903');
}, 6000);
setTimeout(() => {
// remove the custom element
document.querySelector('custom-element').remove();
}, 8000);
</script>
</body>
</html>