markdown 变异观察员

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 变异观察员相关的知识,希望对你有一定的参考价值。

https://blog.sessionstack.com/how-javascript-works-tracking-changes-in-the-dom-using-mutationobserver-86adc7446401#7fb8

## Overview

[MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) is a Web API provided by modern browsers for detecting changes in the DOM. With this API one can listen to newly added or removed nodes, attribute changes or changes in the text content of text nodes.

Why would you want to do that?

There are quite a few cases in which the MutationObserver API can come really handy. For instance:

* You want to notify your web app visitor that some change has occurred on the page he’s currently on.
* You’re working on a new fancy JavaScript framework that loads dynamically JavaScript modules based on how the DOM changes.
* You might be working on a WYSIWYG editor, trying to implement undo/redo functionality. By leveraging the MutationObserver API, you know at any given point what changes have been made, so you can easily undo them.

#### How to use MutationObserver

Implementing `MutationObserver` into your app is rather easy. You need to create a `MutationObserver` instance by passing it a function that would be called every time a mutation has occurred. The first argument of the function is a collection of all mutations which have occurred in a single batch. Each mutation provides information about its type and the changes which have occurred.
```
var mutationObserver = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation);
  });
});
```

The created object has three methods:

* `observe`  —  starts listening for changes. Takes two arguments  —  the DOM node you want to observe and a settings object
* `disconnect`  —  stops listening for changes
* `takeRecords`  —  returns the last batch of changes before the callback has been fired.

The following snippet shows how to start observing:

```
// Starts listening for changes in the root HTML element of the page.
mutationObserver.observe(document.documentElement, {
  attributes: true,
  characterData: true,
  childList: true,
  subtree: true,
  attributeOldValue: true,
  characterDataOldValue: true
});
```
Now, let’s say that you have some very simple div in the DOM:
```
<div id="sample-div" class="test"> Simple div </div>
```
Using jQuery, you canremove the class attribute from that div:
```
$("#sample-div").removeAttr("class");
```
As we have started observing, after calling mutationObserver.observe(...) we’re going to see a log in the console of the respective MutationRecord.

This is the mutation caused by removing the class attribute.

And finally, in order to stop observing the DOM after the job is done, you can do the following:
```
// Stops the MutationObserver from listening for changes.
mutationObserver.disconnect();
```
Nowadays, the MutationObserver is widely supported.

---

### C0de Sample

```
var observer = new MutationObserver(function (mutationsList) {
    for (var i = 0; i < mutationsList.length; i++) {
      var mutation = mutationsList[i];
      if (mutation.type === "attributes") {/* detect attribute changes */
        var elem = mutation.target;
        var $elem = $(elem);
        if (elem.hasAttribute("disabled")) {
          $elem.removeClass("valid").removeClass("input-validation-error");
          if ($elem.data("bs.tooltip")) {
            $elem.tooltip("hide");
          }
        }
      }
    }
});

$(formSelector + " :input:not(button)").each(function (ix, elem) {

    /* subscribe elements to attribute change tracking (mutation observer) mechanism */
    observer.observe(elem, { attributes: true }); /* (observe attribute changes only) */

    /* requiredIf <=> jQuery validator integration */
    if (elem.hasAttribute("data-val-requiredif")) {
      $(elem).attr("data-val-required", $(elem).attr("data-val-requiredif"));
    }

});
```

以上是关于markdown 变异观察员的主要内容,如果未能解决你的问题,请参考以下文章

html 项目分页w变异观察员

markdown 阿波罗:查询或变异方法

javascript javascript tampermonkey添加变异观察者

markdown graphql apollo-client变异警告

JavaScript 中的简单变异观察者示例不起作用

jQuery 选择器可以与 DOM 变异观察者一起使用吗?