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è)重要特性,它能夠讓開發(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)聽器、請(qǐng)求數(shù)據(jù)等等。在這個(gè)時(shí)候,元素已經(jīng)被添加到了文檔中,可以訪問到 DOM 和其他元素。
disconnectedCallback
是在 custom element 從文檔 DOM 中刪除時(shí)被調(diào)用的。這個(gè)回調(diào)函數(shù)通常用于清理一些資源,比如取消事件監(jiān)聽器、停止定時(shí)器等等。在這個(gè)時(shí)候,元素已經(jīng)不再被文檔所包含,無法訪問到 DOM 和其他元素。
adoptedCallback
是在 custom element 被移動(dòng)到新的文檔時(shí)被調(diào)用的。這個(gè)回調(diào)函數(shù)通常用于處理一些文檔級(jí)別的操作,比如重新計(jì)算布局(重排)、修改樣式等等。在這個(gè)時(shí)候,元素已經(jīng)從原來的文檔中移除,并被添加到了新的文檔中。
attributeChangedCallback
是在 custom element 增加、刪除、修改自身屬性時(shí)被調(diào)用的。這個(gè)回調(diào)函數(shù)通常用于處理一些屬性相關(guān)的邏輯,比如根據(jù)屬性值的變化更新元素的樣式、重新渲染元素等等。在這個(gè)時(shí)候,元素的屬性已經(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示例(查看在線示例)。這個(gè)簡單示例只是生成特定大小、顏色的方塊。custom element 看起來像下面這樣:
<custom-square l="100" c="red"></custom-square>
這里,類的構(gòu)造函數(shù)很簡單 — 我們將 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ù)來確保方塊按照定義來顯示;
connectedCallback() { console.log('Custom square element added to page.'); updateStyle(this); }
disconnectedCallback()
和adoptedCallback()
回調(diào)函數(shù)只是簡單地將消息發(fā)送到控制臺(tái),提示我們?cè)厥裁磿r(shí)候從 DOM 中移除、或者什么時(shí)候移動(dòng)到不同的頁面:
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í)行。正如它的屬性所示,我們可以查看屬性的名稱、舊值與新值,以此來對(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)聽這個(gè)屬性。這可以通過定義observedAttributes()
get 函數(shù)來實(shí)現(xiàn),observedAttributes()
函數(shù)體內(nèi)包含一個(gè) return 語句,返回一個(gè)數(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ù)中的一個(gè)重要特性,它能夠讓開發(fā)者更加靈活地控制元素的行為。
通過合理地使用這些回調(diào)函數(shù),可以讓自定義元素更加易用、易維護(hù),提高開發(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獲取當(dāng)前時(shí)間顯示在頁面上并每秒刷新

javascript實(shí)現(xiàn)簡單下拉菜單效果

js如何準(zhǔn)確獲取當(dāng)前頁面url網(wǎng)址信息

基于JS實(shí)現(xiàn)Flappy?Bird游戲的示例代碼