当前位置:网站首页>Web components series (VII) -- life cycle of custom components
Web components series (VII) -- life cycle of custom components
2022-07-05 03:40:00 【Programming samadhi】
Preface
What is meant by ” Life cycle “? seeing the name of a thing one thinks of its function , The life cycle refers to the whole process of an object from its birth to its death , Of course , The specific stage division of the life cycle of different objects may be different .
When we use the front-end component framework , We all know that each component has its own life cycle , After defining the component life cycle , Developers can execute different code logic in different life cycles of components , So as to achieve the role of management components .
In order to make Custom Elements More flexible in use , It also has the ” Life cycle “ Callback function , It allows developers to define methods that can be executed at different stages of the component's life .
Custom Elements Life cycle division
stay Custom Elements In the constructor of , You can specify multiple different callback functions , They will be called at different times of the element's life :
connectedCallback
: When Custom Elements First inserted into document DOM when , Called .disconnectedCallback
: When Custom Elements From the document DOM When deleted in , Called .adoptedCallback
: When Custom Elements When moved to a new document , Called .attributeChangedCallback
: When Custom Elements increase 、 Delete 、 When modifying its properties , Called .
Be careful : The lifecycle callback function of a custom element is used in its constructor .
Use of lifecycle callback function
First look at the effect :
What needs to be noted here is :adoptedCallback The callback is only available when the custom element is moved to a new document ( It's usually iframe) It will be triggered only when it is in .
The code is as follows :
<!--index.html-->
<head>
<style> body {
padding: 50px; } custom-square {
margin: 15px; } iframe {
width: 100%; height: 250px; overflow: hidden; } </style>
</head>
<body>
<h1>Custom Elements Life cycle </h1>
<div>
<button class="add"> Additional Square To DOM</button>
<button class="update"> change Square Properties of </button>
<button class="remove"> remove Square Elements </button>
<button class="move"> Move Square To Iframe</button>
</div>
<iframe src="./other.html"></iframe>
<script src="./square.js"></script>
<script src="./index.js"></script>
</body>
<!--other.html-->
<body>
<h1> This is a other.html</h1>
</body>
// square.js
function updateStyle(elem) {
const shadow = elem.shadowRoot;
shadow.querySelector("style").textContent = ` div { width: ${
elem.getAttribute("l")}px; height: ${
elem.getAttribute("l")}px; background-color: ${
elem.getAttribute("c")}; } `;
}
class Square extends HTMLElement {
static get observedAttributes() {
return ["c", "l"];
}
constructor() {
super();
const shadow = this.attachShadow({
mode: "open" });
const div = document.createElement("div");
const style = document.createElement("style");
shadow.appendChild(style);
shadow.appendChild(div);
}
connectedCallback() {
console.log("custom-square Be mounted to the page ");
updateStyle(this);
}
disconnectedCallback() {
console.log("custom-square Removed from page ");
}
adoptedCallback() {
console.log("custom-square Moved to a new page ");
}
attributeChangedCallback(name, oldValue, newValue) {
console.log("custom-square The attribute value is changed ");
updateStyle(this);
}
}
customElements.define("custom-square", Square);
// index.js
const add = document.querySelector(".add");
const update = document.querySelector(".update");
const remove = document.querySelector(".remove");
const move = document.querySelector(".move");
let square;
update.disabled = true;
remove.disabled = true;
function random(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
add.onclick = function () {
// Create a custom square element
square = document.createElement("custom-square");
square.setAttribute("l", "100");
square.setAttribute("c", "red");
document.body.appendChild(square);
update.disabled = false;
remove.disabled = false;
add.disabled = true;
};
update.onclick = function () {
// Randomly update square's attributes
square.setAttribute("l", random(50, 200));
square.setAttribute("c", `rgb(${
random(0, 255)}, ${
random(0, 255)}, ${
random(0, 255)})`);
};
remove.onclick = function () {
// Remove the square
document.body.removeChild(square);
update.disabled = true;
remove.disabled = true;
add.disabled = false;
};
update.onclick = function () {
// Randomly update square's attributes
square.setAttribute("l", random(50, 200));
square.setAttribute("c", `rgb(${
random(0, 255)}, ${
random(0, 255)}, ${
random(0, 255)})`);
};
move.onclick = function () {
window.frames[0].document.body.appendChild(square);
}
Conclusion
That's all Custom Elements A simple example of using the lifecycle callback function , I hope it helped you !
Custom Elements In the callback function of ,adoptedCallback There are few usage scenarios , This needs attention .
- ~
- The end of this paper , Thank you for reading !
~
Learn interesting knowledge , Make interesting friends , Create interesting souls !
Hello everyone , I am a 〖 The samadhi of programming 〗 The author of Hermit King , My official account is 『 The samadhi of programming 』, Welcome to your attention , I hope you can give me more advice !
边栏推荐
- The perfect car for successful people: BMW X7! Superior performance, excellent comfort and safety
- Technology sharing swift defense programming
- glibc strlen 实现方式分析
- [punch in questions] integrated daily 5-question sharing (phase III)
- 【软件逆向-基础知识】分析方法、汇编指令体系结构
- 花了2晚,拿到了吴恩达@斯坦福大学的机器学习课程证书
- 【PHP特性-变量覆盖】函数的使用不当、配置不当、代码逻辑漏洞
- Easy processing of ten-year futures and stock market data -- Application of tdengine in Tongxinyuan fund
- Why do some programmers change careers before they are 30?
- Some enterprise interview questions of unity interview
猜你喜欢
花了2晚,拿到了吴恩达@斯坦福大学的机器学习课程证书
How to define a unified response object gracefully
2. Common request methods
Azkaban overview
Three line by line explanations of the source code of anchor free series network yolox (a total of ten articles, which are guaranteed to be explained line by line. After reading it, you can change the
Kbp206-asemi rectifier bridge kbp206
Redis6-01nosql database
v-if VS v-show 2.0
[software reverse - basic knowledge] analysis method, assembly instruction architecture
Clickhouse同步mysql(基于物化引擎)
随机推荐
C file in keil cannot be compiled
【软件逆向-基础知识】分析方法、汇编指令体系结构
[2022 repair version] community scanning code into group activity code to drain the complete operation source code / connect the contract free payment interface / promote the normal binding of subordi
[move pictures up, down, left and right through the keyboard in JS]
New interesting test applet source code_ Test available
SQL injection exercise -- sqli Labs
Nmap使用手册学习记录
[groovy] loop control (number injection function implements loop | times function | upto function | downto function | step function | closure can be written outside as the final parameter)
Une question est de savoir si Flink SQL CDC peut définir le parallélisme. Si le parallélisme est supérieur à 1, il y aura un problème d'ordre?
LeetCode146. LRU cache
Delphi free memory
Usage scenarios and solutions of ledger sharing
There is a question about whether the parallelism can be set for Flink SQL CDC. If the parallelism is greater than 1, will there be a sequence problem?
LeetCode 237. Delete nodes in the linked list
Pat class a 1160 forever (class B 1104 forever)
How to define a unified response object gracefully
线程基础知识
1. Five layer network model
Kubernetes -- cluster expansion principle
【无标题】