首页 > 解决方案 > MutationObserver 作为对象的属性在断开连接后无法立即观察

问题描述

我有以下课程:

class CustomOption extends HTMLElement {
    constructor() {
        super();
        this.addEventListener("mousedown", this.isSelecting);
        this.addEventListener("mouseup", this.setSelection);
        this.addEventListener("mouseenter", this.startHover);
        var customOption = this;
        this.observer = new MutationObserver(function(mutationsList, observer) {
            customOption.customSelect.adjustSize();
            customOption.backgroundColor = customOption.style.backgroundColor;
            if (customOption.customSelected.hoveredOption == customOption) {
                customOption.setBackgroundColorUnobtrusively(customOption.selectedColor);
            }
        });
        this.observer.observe(this, { childList: true, characterData: true, subtree: true, attributes: true, attributeFilter: ["style"] });
    }

    ...

    setBackgroundColorUnobtrusively(color) {
        this.observer.disconnect();
        this.style.backgroundColor = color;
        this.observer.observe(this, { characterData: true, subtree: true, attributes: true, attributeFilter: ["style"] });
    }
}

当我调用setBackgroundColorUnobtrusivelyCustomOption 对象时,观察者实际上并没有再次开始观察。但是,如果我在浏览器中转到控制台并以这种方式执行此操作,则在再次调用后它仍然disconnect有效observe

var x = document.getElementsByTagName("custom-option")[0];
var observer = new MutationObserver(function(mutationsList, observer) {
    x.customSelect.adjustSize();
    x.backgroundColor = x.style.backgroundColor;
    if (x.customSelected.hoveredOption == x) {
        x.setBackgroundColorUnobtrusively(x.selectedColor);
    }
});
observer.disconnect();
x.style.backgroundColor = "white";
observer.observe(x, { characterData: true, subtree: true, attributes: true, attributeFilter: ["style"] });

任何线索为什么会这样?它与对 MutationObserver 的引用有关吗?我已经完成了检查,并且this似乎setBackgroundColorUnobtrusively已正确绑定。这让我感觉很奇怪...

标签: javascriptmutation-observers

解决方案


这个问题很简单:

在构造函数中,我在调用时包含childList: true选项observe参数中,但是,当我再次开始观察时setBackgroundColorUnobtrusively,我没有包含该选项。

要点:在观察中列出您的选项时要小心,并确保您知道它们的作用!

有关选项的更多信息observe


推荐阅读