Implementing MutationObserver in place of DOMSubtreeModified

时光毁灭记忆、已成空白 提交于 2019-12-22 08:17:31

问题


I have a select[multiple] which I have given a class custom-multiselect on my page for which I am catching the DOMSubtreeModified event as follows:

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);
    });
});

This approach works flawlessly. I want to convert the DOMSubtreeModified function into MutationObserver since DOMSubtreeModified is depreciated.

So I did something like this:

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
});

But I end up getting error

TypeError: The expression cannot be converted to return the specified type.

How can I convert my DOMSubtreeModified event to be observed by the MutationObserver?


回答1:


  • Put the code in place of the old DOM event and use your sel variable as the observation target;
  • Use childList option in MutationObserver because subtree doesn't specify what to look for;
  • There's no need to check the mutations since you subscribe only to one type.

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

    new MutationObserver(function() {
        adjustHeight(sel);
    }).observe(sel, {childList: true, subtree: true});
});

Or, if you like .bind for some reason:

new MutationObserver(adjustHeight.bind(null, sel))
    .observe(sel, {childList: true, subtree: true});


来源:https://stackoverflow.com/questions/41971140/implementing-mutationobserver-in-place-of-domsubtreemodified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!