实施 MutationObserver 代替 DOMSubtreeModified
Implementing MutationObserver in place of DOMSubtreeModified
我有一个 select[multiple]
,我在我的页面上给出了一个 class custom-multiselect
,我正在为其捕获 DOMSubtreeModified
事件,如下所示:
HTML:
<select class="custom-multiselect"></select>
JQuery:
$('.custom-multiselect').each(function (i, select) {
var sel = this;
adjustHeight(sel); //Custom function
//Binding DOMSubtreeModified to catch if the select list gets modified by the user
$(sel).on('DOMSubtreeModified', function () {
adjustHeight(sel);
});
//For Internet Explorer
$(sel).on('propertychange', function () {
adjustHeight(sel);
});
});
这种方法完美无缺。我想将 DOMSubtreeModified
函数转换为 MutationObserver
,因为 DOMSubtreeModified
已贬值。
所以我做了这样的事情:
var observer = new MutationObserver(function (mutation) {
mutation.forEach(function (m) {
if (m.type == 'subtree') {
adjustHeight(this);//Can I use m.target here?
}
});
});
observer.observe(document.querySelector('select.custom-multiselect'), {
subtree: true
});
但我最终得到了错误
TypeError: The expression cannot be converted to return the specified type.
如何将我的 DOMSubtreeModified
事件转换为由 MutationObserver
观察?
- 将代码替换为旧的 DOM 事件,并使用您的
sel
变量作为观察目标;
- 在 MutationObserver 中使用
childList
选项,因为 subtree
没有指定要查找的内容;
- 无需检查突变,因为您只订阅了一种类型。
$('.custom-multiselect').each(function() {
var sel = this;
adjustHeight(sel);
new MutationObserver(function() {
adjustHeight(sel);
}).observe(sel, {childList: true, subtree: true});
});
或者,如果您出于某种原因喜欢.bind
:
new MutationObserver(adjustHeight.bind(null, sel))
.observe(sel, {childList: true, subtree: true});
我有一个 select[multiple]
,我在我的页面上给出了一个 class custom-multiselect
,我正在为其捕获 DOMSubtreeModified
事件,如下所示:
HTML:
<select class="custom-multiselect"></select>
JQuery:
$('.custom-multiselect').each(function (i, select) {
var sel = this;
adjustHeight(sel); //Custom function
//Binding DOMSubtreeModified to catch if the select list gets modified by the user
$(sel).on('DOMSubtreeModified', function () {
adjustHeight(sel);
});
//For Internet Explorer
$(sel).on('propertychange', function () {
adjustHeight(sel);
});
});
这种方法完美无缺。我想将 DOMSubtreeModified
函数转换为 MutationObserver
,因为 DOMSubtreeModified
已贬值。
所以我做了这样的事情:
var observer = new MutationObserver(function (mutation) {
mutation.forEach(function (m) {
if (m.type == 'subtree') {
adjustHeight(this);//Can I use m.target here?
}
});
});
observer.observe(document.querySelector('select.custom-multiselect'), {
subtree: true
});
但我最终得到了错误
TypeError: The expression cannot be converted to return the specified type.
如何将我的 DOMSubtreeModified
事件转换为由 MutationObserver
观察?
- 将代码替换为旧的 DOM 事件,并使用您的
sel
变量作为观察目标; - 在 MutationObserver 中使用
childList
选项,因为subtree
没有指定要查找的内容; - 无需检查突变,因为您只订阅了一种类型。
$('.custom-multiselect').each(function() {
var sel = this;
adjustHeight(sel);
new MutationObserver(function() {
adjustHeight(sel);
}).observe(sel, {childList: true, subtree: true});
});
或者,如果您出于某种原因喜欢.bind
:
new MutationObserver(adjustHeight.bind(null, sel))
.observe(sel, {childList: true, subtree: true});