Web?Components使用生命周期回調(diào)函數(shù)實(shí)例詳解
custom element構(gòu)造函數(shù)
在 custom element 的構(gòu)造函數(shù)中,可以指定多個不同的回調(diào)函數(shù),它們將會在元素的不同生命時期被調(diào)用。這是 Web Components 技術(shù)中的一個重要特性,它能夠讓開發(fā)者更加靈活地控制元素的行為
connectedCallback:當(dāng) custom element 首次被插入文檔 DOM 時,被調(diào)用。disconnectedCallback:當(dāng) custom element 從文檔 DOM 中刪除時,被調(diào)用。adoptedCallback:當(dāng) custom element 被移動到新的文檔時,被調(diào)用。attributeChangedCallback: 當(dāng) custom element 增加、刪除、修改自身屬性時,被調(diào)用。
其中,connectedCallback 是在 custom element 首次被插入文檔 DOM 時被調(diào)用的。這個回調(diào)函數(shù)通常用于執(zhí)行一些初始化操作,比如添加事件監(jiān)聽器、請求數(shù)據(jù)等等。在這個時候,元素已經(jīng)被添加到了文檔中,可以訪問到 DOM 和其他元素。
disconnectedCallback 是在 custom element 從文檔 DOM 中刪除時被調(diào)用的。這個回調(diào)函數(shù)通常用于清理一些資源,比如取消事件監(jiān)聽器、停止定時器等等。在這個時候,元素已經(jīng)不再被文檔所包含,無法訪問到 DOM 和其他元素。
adoptedCallback 是在 custom element 被移動到新的文檔時被調(diào)用的。這個回調(diào)函數(shù)通常用于處理一些文檔級別的操作,比如重新計算布局(重排)、修改樣式等等。在這個時候,元素已經(jīng)從原來的文檔中移除,并被添加到了新的文檔中。
attributeChangedCallback 是在 custom element 增加、刪除、修改自身屬性時被調(diào)用的。這個回調(diào)函數(shù)通常用于處理一些屬性相關(guān)的邏輯,比如根據(jù)屬性值的變化更新元素的樣式、重新渲染元素等等。在這個時候,元素的屬性已經(jīng)被修改,可以通過新的屬性值來進(jìn)行相應(yīng)的處理。
需要注意的是,這些回調(diào)函數(shù)都是可選的,開發(fā)者可以根據(jù)實(shí)際需求來選擇使用哪些回調(diào)函數(shù)。另外,這些回調(diào)函數(shù)只能在 custom element 的構(gòu)造函數(shù)中進(jìn)行定義,不能在元素實(shí)例中進(jìn)行修改。
用法示例
我們來看一下它們的一下用法示例。下面的代碼出自life-cycle-callbacks示例(查看在線示例)。這個簡單示例只是生成特定大小、顏色的方塊。custom element 看起來像下面這樣:
<custom-square l="100" c="red"></custom-square>
這里,類的構(gòu)造函數(shù)很簡單 — 我們將 shadow DOM 附加到元素上,然后將一個<div>元素和<style>元素附加到 shadow root 上:
var shadow = this.attachShadow({ mode: "open" });
var div = document.createElement("div");
var style = document.createElement("style");
shadow.appendChild(style);
shadow.appendChild(div);示例中的關(guān)鍵函數(shù)是 updateStyle()—它接受一個元素作為參數(shù),然后獲取該元素的 shadow root,找到<style>元素,并添加width,height以及background-color樣式。
function updateStyle(elem) {
var shadow = elem.shadowRoot;
shadow.querySelector("style").textContent = `
div {
width: ${elem.getAttribute("l")}px;
height: ${elem.getAttribute("l")}px;
background-color: ${elem.getAttribute("c")};
}
`;
}實(shí)際的更新操作是在生命周期的回調(diào)函數(shù)中處理的,我們在構(gòu)造函數(shù)中設(shè)定類這些回調(diào)函數(shù)。當(dāng)元素插入到 DOM 中時,connectedCallback()函數(shù)將會執(zhí)行 — 在該函數(shù)中,我們執(zhí)行updateStyle() 函數(shù)來確保方塊按照定義來顯示;
connectedCallback() {
console.log('Custom square element added to page.');
updateStyle(this);
}disconnectedCallback()和adoptedCallback()回調(diào)函數(shù)只是簡單地將消息發(fā)送到控制臺,提示我們元素什么時候從 DOM 中移除、或者什么時候移動到不同的頁面:
disconnectedCallback() {
console.log('Custom square element removed from page.');
}
adoptedCallback() {
console.log('Custom square element moved to new page.');
}每當(dāng)元素的屬性變化時,attributeChangedCallback()回調(diào)函數(shù)會執(zhí)行。正如它的屬性所示,我們可以查看屬性的名稱、舊值與新值,以此來對元素屬性做單獨(dú)的操作。在當(dāng)前的示例中,我們只是再次執(zhí)行了updateStyle()函數(shù),以確保方塊的樣式在元素屬性值變化后得以更新:
attributeChangedCallback(name, oldValue, newValue) {
console.log('Custom square element attributes changed.');
updateStyle(this);
}需要注意的是,如果需要在元素屬性變化后,觸發(fā)attributeChangedCallback()回調(diào)函數(shù),你必須監(jiān)聽這個屬性。這可以通過定義observedAttributes() get 函數(shù)來實(shí)現(xiàn),observedAttributes()函數(shù)體內(nèi)包含一個 return 語句,返回一個數(shù)組,包含了需要監(jiān)聽的屬性名稱:
static get observedAttributes() {return ['w', 'l']; }完整代碼
// Create a class for the element
class Square extends HTMLElement {
// Specify observed attributes so that
// attributeChangedCallback will work
static get observedAttributes() {
return ['c', 'l'];
}
constructor() {
// Always call super first in 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 element added to page.');
updateStyle(this);
}
disconnectedCallback() {
console.log('Custom square element removed from page.');
}
adoptedCallback() {
console.log('Custom square element moved to new page.');
}
attributeChangedCallback(name, oldValue, newValue) {
console.log('Custom square element attributes changed.');
updateStyle(this);
}
}
customElements.define('custom-square', Square);
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')};
}
`;
}
const add = document.querySelector('.add');
const update = document.querySelector('.update');
const remove = document.querySelector('.remove');
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;
};Custom element 的生命周期回調(diào)函數(shù)是 Web Components 技術(shù)中的一個重要特性,它能夠讓開發(fā)者更加靈活地控制元素的行為。
通過合理地使用這些回調(diào)函數(shù),可以讓自定義元素更加易用、易維護(hù),提高開發(fā)效率和代碼質(zhì)量。
以上就是Web Components使用生命周期回調(diào)函數(shù)實(shí)例詳解的詳細(xì)內(nèi)容,更多關(guān)于Web Components生命周期函數(shù)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
javascript實(shí)現(xiàn)簡單下拉菜單效果
js如何準(zhǔn)確獲取當(dāng)前頁面url網(wǎng)址信息
基于JS實(shí)現(xiàn)Flappy?Bird游戲的示例代碼

