attributeChangedCallback

attributeChangedCallback

在以下代码中,即使创建,更改或删除了“内容”属性,attributeChangedCallback也不会被调用。

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给出的最佳实践,我希望在attributeChangedCallback中发生属性更改的副作用(在本例中为innerHTML的更新)。但是,当我将此更新移至设置程序时,代码可以正常工作。

最佳答案

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');
            }
        }

    }


你把父母和孩子混在一起

您正在元素(►父元素)上定义一个setter

当您执行this.button.setAttribute('content', val);

您正在更改元素(►子元素)的属性

这将永远不会触发(►parent)的attributeChangedCallback
因为它的属性没有改变

您必须使用.getRootNode()和/或.host来“向上DOM”以设置父元素的属性。

或使用Custom Events(冒充DOM)通知父母孩子已经做过/更改过的东西

我想你想做

set content(val) {
        //  loose ==null comparison for null AND undefined,
        //  element.content=null; will remove the attribute
        if (val==null)
            this.removeAttribute('content');
        else
        //  but you DO want .content(0) (0==false) set as "0"
            this.setAttribute('content', val);
    }

08-15 15:15