Web?Components使用生命周期回調(diào)函數(shù)實(shí)例詳解
custom element構(gòu)造函數(shù)
在 custom element 的構(gòu)造函數(shù)中,可以指定多個(gè)不同的回調(diào)函數(shù),它們將會(huì)在元素的不同生命時(shí)期被調(diào)用。這是 Web Components 技術(shù)中的一個(gè)重要特性,它能夠讓開(kāi)發(fā)者更加靈活地控制元素的行為
connectedCallback:當(dāng) custom element 首次被插入文檔 DOM 時(shí),被調(diào)用。disconnectedCallback:當(dāng) custom element 從文檔 DOM 中刪除時(shí),被調(diào)用。adoptedCallback:當(dāng) custom element 被移動(dòng)到新的文檔時(shí),被調(diào)用。attributeChangedCallback: 當(dāng) custom element 增加、刪除、修改自身屬性時(shí),被調(diào)用。
其中,connectedCallback 是在 custom element 首次被插入文檔 DOM 時(shí)被調(diào)用的。這個(gè)回調(diào)函數(shù)通常用于執(zhí)行一些初始化操作,比如添加事件監(jiān)聽(tīng)器、請(qǐng)求數(shù)據(jù)等等。在這個(gè)時(shí)候,元素已經(jīng)被添加到了文檔中,可以訪問(wèn)到 DOM 和其他元素。
disconnectedCallback 是在 custom element 從文檔 DOM 中刪除時(shí)被調(diào)用的。這個(gè)回調(diào)函數(shù)通常用于清理一些資源,比如取消事件監(jiān)聽(tīng)器、停止定時(shí)器等等。在這個(gè)時(shí)候,元素已經(jīng)不再被文檔所包含,無(wú)法訪問(wèn)到 DOM 和其他元素。
adoptedCallback 是在 custom element 被移動(dòng)到新的文檔時(shí)被調(diào)用的。這個(gè)回調(diào)函數(shù)通常用于處理一些文檔級(jí)別的操作,比如重新計(jì)算布局(重排)、修改樣式等等。在這個(gè)時(shí)候,元素已經(jīng)從原來(lái)的文檔中移除,并被添加到了新的文檔中。
attributeChangedCallback 是在 custom element 增加、刪除、修改自身屬性時(shí)被調(diào)用的。這個(gè)回調(diào)函數(shù)通常用于處理一些屬性相關(guān)的邏輯,比如根據(jù)屬性值的變化更新元素的樣式、重新渲染元素等等。在這個(gè)時(shí)候,元素的屬性已經(jīng)被修改,可以通過(guò)新的屬性值來(lái)進(jìn)行相應(yīng)的處理。
需要注意的是,這些回調(diào)函數(shù)都是可選的,開(kāi)發(fā)者可以根據(jù)實(shí)際需求來(lái)選擇使用哪些回調(diào)函數(shù)。另外,這些回調(diào)函數(shù)只能在 custom element 的構(gòu)造函數(shù)中進(jìn)行定義,不能在元素實(shí)例中進(jìn)行修改。
用法示例
我們來(lái)看一下它們的一下用法示例。下面的代碼出自life-cycle-callbacks示例(查看在線示例)。這個(gè)簡(jiǎn)單示例只是生成特定大小、顏色的方塊。custom element 看起來(lái)像下面這樣:
<custom-square l="100" c="red"></custom-square>
這里,類的構(gòu)造函數(shù)很簡(jiǎn)單 — 我們將 shadow DOM 附加到元素上,然后將一個(gè)<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()—它接受一個(gè)元素作為參數(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ù)中處理的,我們?cè)跇?gòu)造函數(shù)中設(shè)定類這些回調(diào)函數(shù)。當(dāng)元素插入到 DOM 中時(shí),connectedCallback()函數(shù)將會(huì)執(zhí)行 — 在該函數(shù)中,我們執(zhí)行updateStyle() 函數(shù)來(lái)確保方塊按照定義來(lái)顯示;
connectedCallback() {
console.log('Custom square element added to page.');
updateStyle(this);
}disconnectedCallback()和adoptedCallback()回調(diào)函數(shù)只是簡(jiǎn)單地將消息發(fā)送到控制臺(tái),提示我們?cè)厥裁磿r(shí)候從 DOM 中移除、或者什么時(shí)候移動(dòng)到不同的頁(yè)面:
disconnectedCallback() {
console.log('Custom square element removed from page.');
}
adoptedCallback() {
console.log('Custom square element moved to new page.');
}每當(dāng)元素的屬性變化時(shí),attributeChangedCallback()回調(diào)函數(shù)會(huì)執(zhí)行。正如它的屬性所示,我們可以查看屬性的名稱、舊值與新值,以此來(lái)對(duì)元素屬性做單獨(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)聽(tīng)這個(gè)屬性。這可以通過(guò)定義observedAttributes() get 函數(shù)來(lái)實(shí)現(xiàn),observedAttributes()函數(shù)體內(nèi)包含一個(gè) return 語(yǔ)句,返回一個(gè)數(shù)組,包含了需要監(jiān)聽(tīng)的屬性名稱:
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ù)中的一個(gè)重要特性,它能夠讓開(kāi)發(fā)者更加靈活地控制元素的行為。
通過(guò)合理地使用這些回調(diào)函數(shù),可以讓自定義元素更加易用、易維護(hù),提高開(kāi)發(fā)效率和代碼質(zhì)量。
以上就是Web Components使用生命周期回調(diào)函數(shù)實(shí)例詳解的詳細(xì)內(nèi)容,更多關(guān)于Web Components生命周期函數(shù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
淺談JS使用[ ]來(lái)訪問(wèn)對(duì)象屬性
下面小編就為大家?guī)?lái)一篇淺談JS使用[ ]來(lái)訪問(wèn)對(duì)象屬性。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-09-09
JavaScript中“基本類型”之爭(zhēng)小結(jié)
所謂“基本類型(primitive types)”的概念ECMAScript(V3,V5)中壓根就沒(méi)有,它只是將類型分為6種,感興趣的朋友可以參考下2013-01-01
javascript實(shí)現(xiàn)很浪漫的氣泡冒出特效
這篇文章主要為大家詳細(xì)介紹了javascript實(shí)現(xiàn)很浪漫的氣泡冒出特效,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2015-11-11
uniapp uni-swipe-action 滑動(dòng)操作狀態(tài)恢復(fù)功能實(shí)現(xiàn)
按照uni-app官方文檔的寫法,當(dāng)前一條滑動(dòng)確認(rèn)之后頁(yè)面列表刷新但是滑動(dòng)的狀態(tài)還在,我們需要在滑動(dòng)確認(rèn)之后 頁(yè)面刷新 滑動(dòng)狀態(tài)恢復(fù),下面小編給大家分享uniapp uni-swipe-action 滑動(dòng)操作狀態(tài)恢復(fù)功能實(shí)現(xiàn),感興趣的朋友跟隨小編一起看看吧2024-06-06
JavaScript數(shù)據(jù)類型的存儲(chǔ)方法詳解
JavaScript中基本數(shù)據(jù)類型和引用數(shù)據(jù)類型是如何存儲(chǔ)的呢?下面通過(guò)本文給大家分享js數(shù)據(jù)類型的存儲(chǔ)方法,需要的朋友參考下吧2017-08-08
怎樣用Javascript實(shí)現(xiàn)單例模式
這篇文章主要介紹了怎樣用Javascript實(shí)現(xiàn)單例模式,想學(xué)習(xí)設(shè)計(jì)模式的同學(xué),可以參考下2021-04-04
layer彈窗在鍵盤按回車將反復(fù)刷新的實(shí)現(xiàn)方法
今天小編就為大家分享一篇layer彈窗在鍵盤按回車將反復(fù)刷新的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-09-09
JavaScript中對(duì)于Map的簡(jiǎn)單介紹
JavaScript的Map是鍵值對(duì)數(shù)據(jù)結(jié)構(gòu),支持任意類型鍵,保持插入順序,性能優(yōu)于Object,這篇文章主要介紹了JavaScript中對(duì)于Map的相關(guān)資料,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-06-06

