【问题标题】:MutationObserver as property of object fails to observe immediately after being disconnectedMutationObserver 作为对象的属性在断开连接后无法立即观察
【发布时间】:2021-01-19 07:26:05
【问题描述】:

我有以下课程:

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"] });
    }
}

当我在 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, { characterData: true, subtree: true, attributes: true, attributeFilter: ["style"] });

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

【问题讨论】:

  • 唯一的区别是它在this 中使用了您的自定义元素,所以我猜它与标准 DOM 方法返回的实际 DOM 元素有所不同。
  • 奇怪的是,我将thissetBackgroundColorUnobtrusively 中DOM 中的第一个CustomOption 元素(我用来测试其观察者是否正常工作的元素)进行了比较,然后它又回来了说实话……
  • 如果我在 setBackgroundColorUnobtrusively 中创建一个新的 MutationObserver 而不是重用旧的,那么最终也可以正常工作。
  • 你的意思是this === document.getElementsByTagName("custom-option")[0]
  • 是的,我就是这个意思。

标签: javascript mutation-observers


【解决方案1】:

问题很简单:

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

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

More info on options for observe

【讨论】:

  • 您应该创建一个单独的方法,例如 startObserving 并从构造函数和其他函数中调用它。
猜你喜欢
  • 2016-02-14
  • 2020-02-07
  • 2018-02-10
  • 2019-07-20
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多