本文介绍了代替DOMSubtreeModified实现MutationObserver的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个select[multiple],我在页面上给出了一个类custom-multiselect,为此,我正在捕获DOMSubtreeModified事件,如下所示:

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

这种方法完美无缺.我想将DOMSubtreeModified函数转换为MutationObserver,因为DOMSubtreeModified已贬值.

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

但是我最终遇到了错误

如何将我的DOMSubtreeModified事件转换为MutationObserver所观察到的?

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

推荐答案

  • 将代码替换旧的DOM事件,并使用您的sel变量作为观察目标;
  • 在MutationObserver中使用childList选项,因为subtree没有指定要查找的内容;
  • 由于您只订阅一种类型,因此无需检查突变.
    • 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});
      });
      

      或者,如果您出于某些原因喜欢.bind:

      Or, if you like .bind for some reason:

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

      这篇关于代替DOMSubtreeModified实现MutationObserver的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 17:33