javascript - 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"] });
}
}
当我调用setBackgroundColorUnobtrusively
CustomOption 对象时,观察者实际上并没有再次开始观察。但是,如果我在浏览器中转到控制台并以这种方式执行此操作,则在再次调用后它仍然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
已正确绑定。这让我感觉很奇怪...
解决方案
这个问题很简单:
在构造函数中,我在调用时包含childList: true
在选项observe
参数中,但是,当我再次开始观察时setBackgroundColorUnobtrusively
,我没有包含该选项。
要点:在观察中列出您的选项时要小心,并确保您知道它们的作用!
推荐阅读
- python - 安装本地 python 包时遇到问题
- python - 列不是熊猫数据框的列
- java - 如何在线调用 Rest Api 端点?如何将我的代码放入真实服务器
- python - 如何根据类型取消选择 pydatatable 列?
- docker - 将 Django 部署到 App Engine 柔性环境 - 超时错误响应:[4]
- python - python - 召回浏览过的文件
- android - Android 5 中的崩溃 - 在 onResume 中抛出 IllegalStateException
- mysql - 在 my.cnf 文件中,将 bind-address 更改为 127.0.0.1 并且它仍然允许远程连接
- spring - 如何在春季加载多个骆驼上下文
- java - 无论如何使用java程序在docker容器中获取主机Mac和IP地址