【发布时间】:2020-06-04 17:58:31
【问题描述】:
在以下代码中,attributeChangedCallback 永远不会被调用,即使 'content' 属性被创建、更改或删除。
class Square extends HTMLElement {
static get observedAttributes() {
return ['content'];
}
constructor(val) {
super();
console.log('inside constructor');
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(document.createElement('button'));
this.button = this.shadowRoot.querySelector('button');
this.button.className = "square";
this.content = val;
console.log('constructor ended');
}
get content() {
console.log('inside getter');
return this.button.getAttribute('content');
}
set content(val) {
console.log('setter being executed, val being: ', val);
// pass null to represent empty square
if (val !== null) {
this.button.setAttribute('content', val);
} else {
if (this.button.hasAttribute('content')) {
this.button.removeAttribute('content');
}
}
}
connectedCallback() {
//console.log('connected callback being executed now');
}
// not working :(
attributeChangedCallback(name, oldValue, newValue) {
console.log('attribute changed callback being executed now');
if (name === 'content') {
this.button.innerHTML = newValue?newValue:" ";
}
}
}
customElements.define('square-box', Square);
根据here 给出的最佳实践,我希望属性更改的副作用(在我的例子中更新innerHTML)发生在attributeChangedCallback 中。但是,当我将此更新移动到设置器时,代码可以正常工作。
【问题讨论】:
标签: javascript html web-component custom-element