实现MutationObserver代替DOMSubtreeModified

pro*_*mar 4 javascript jquery dom mutation-observers

我有一个select[multiple]custom-multiselect在我的页面上给我的课程,我正在抓住这个DOMSubtreeModified事件如下:

HTML:

<select class="custom-multiselect"></select>
Run Code Online (Sandbox Code Playgroud)

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);
    });
});
Run Code Online (Sandbox Code Playgroud)

这种方法完美无瑕.我想将转换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
});
Run Code Online (Sandbox Code Playgroud)

但我最终得到错误

TypeError:无法转换表达式以返回指定的类型.

如何将我的DOMSubtreeModified事件转换为由MutationObserver

wOx*_*xOm 8

  • 将代码放在旧DOM事件的位置,并使用您的sel变量作为观察目标;
  • 使用childListMutationObserver中的选项,因为subtree没有指定要查找的内容;
  • 因为您只订阅了一种类型,所以无需检查突变.

$('.custom-multiselect').each(function() {
    var sel = this;
    adjustHeight(sel);

    new MutationObserver(function() {
        adjustHeight(sel);
    }).observe(sel, {childList: true, subtree: true});
});
Run Code Online (Sandbox Code Playgroud)

或者,如果你喜欢.bind某些原因:

new MutationObserver(adjustHeight.bind(null, sel))
    .observe(sel, {childList: true, subtree: true});
Run Code Online (Sandbox Code Playgroud)