【发布时间】: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 时,观察者实际上并没有再次开始观察。但是,如果我在浏览器中转到控制台并以这种方式执行此操作,则在再次调用 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 的引用有关吗?我已经完成了检查,setBackgroundColorUnobtrusively 中的this 似乎绑定正确。这让我感觉很奇怪......
【问题讨论】:
-
唯一的区别是它在
this中使用了您的自定义元素,所以我猜它与标准 DOM 方法返回的实际 DOM 元素有所不同。 -
奇怪的是,我将
this与setBackgroundColorUnobtrusively中DOM 中的第一个CustomOption 元素(我用来测试其观察者是否正常工作的元素)进行了比较,然后它又回来了说实话…… -
如果我在
setBackgroundColorUnobtrusively中创建一个新的 MutationObserver 而不是重用旧的,那么最终也可以正常工作。 -
你的意思是
this === document.getElementsByTagName("custom-option")[0]? -
是的,我就是这个意思。
标签: javascript mutation-observers