问题描述
我有以下课程:
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
时,观察者实际上并没有再次开始观察。但是,如果我在浏览器中进入控制台并以这种方式进行操作,则在再次调用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,attributeFilter: ["style"] });
有什么线索可能会这样吗?它与对MutationObserver的引用有关吗?我已经完成检查,并且this
中的setBackgroundColorUnobtrusively
似乎已正确绑定。这让我感到很奇怪...
解决方法
问题很简单:
在构造函数中,调用childList: true
时在 options 参数中包含observe
,但是,当我再次在setBackgroundColorUnobtrusively
中观察时,我无法包括该选项。
要点:在观察中列出您的选项时要小心,并确保您知道它们的作用!