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,attributeFilter: ["style"] });
    }
}

当我在CustomOption对象上调用setBackgroundColorUnobtrusively时,观察者实际上并没有再次开始观察。但是,如果我在浏览器中进入控制台并以这种方式进行操作,则在再次调用disconnectobserve之后它仍然可以工作:

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,attributeFilter: ["style"] });

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

解决方法

问题很简单:

在构造函数中,调用childList: true时在 options 参数中包含observe,但是,当我再次在setBackgroundColorUnobtrusively中观察时,我无法包括该选项。

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

More info on options for observe