<n-checkbox checked>ITEM1</n-checkbox>
// 建立模版
const template = document.createElement('template')
template.innerHTML = `
<label>
<input type="checkbox" />
<slot />
</label>
`
// 創建自定義元素建構式
class nCheckbox extends HTMLElement {
constructor() {
// 呼叫父層屬性
super()
// 自定義元素 建立 shadowDOM
const shadow = this.attachShadow({ mode: 'open' })
// 將模版寫入 shadowDOM
shadow.append(template.content.cloneNode(true))
// 將 shadowDOM 內 checkbox 寫入屬性 (方便之後操作)
this.shadowCheckboxEl = shadow.querySelector('input[type="checkbox"]')
}
// 監聽 自定義元素 指定屬性
static get observedAttributes() {
// 監聽元素的 checked 屬性
return ['checked']
}
// 當 自定義元素 屬性改變執行函式
attributeChangedCallback(name, oldValue, newValue) {
if (name !== 'checked') return false
// 屬性內容為字串,轉變為 boolean
const newStatus = newValue !== null && newValue !== 'false'
this.setShadowCheckbox(newStatus)
}
// 當 自定義元素 插入 document hook
connectedCallback() {
console.log(`connectedCallback`)
this.shadowCheckboxEl.addEventListener('change', () => {
this.setCustomCheckbox(this.shadowCheckboxEl.checked)
})
}
// 設置 自定義元素 `checked` 屬性
setCustomCheckbox(newValue) {
this.setAttribute('checked', newValue)
}
// 設置 shadowDOM 內 checkbox 元素 checked 狀態
setShadowCheckbox(newValue) {
this.shadowCheckboxEl.checked = newValue
}
}
customElements.define('n-checkbox', nCheckbox)
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.