본문 바로가기
카테고리 없음

[팁] MutationObserver에 대해 알아보자

by marble25 2023. 1. 10.

MutationObserver는 Web API로 DOM 변경을 감지할 때 사용한다.

MutationObserver - Web API | MDN

// 대상 node 선택
var target = document.getElementById('some-id');

// 감시자 인스턴스 만들기
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });
});

// 감시자의 설정:
var config = { attributes: true, childList: true, characterData: true };

// 감시자 옵션 포함, 대상 노드에 전달
observer.observe(target, config);

// 감시를 중지 가능
observer.disconnect();

config에는 감시할 옵션들을 선택할 수 있는데, 다음과 같은 옵션이 있다.

  • childList: child element의 추가와 삭제
  • attributes: target의 attribute의 변경
  • characterData: target의 text data 변경
  • subtree: target과 target의 descendent의 변경

콜백으로 들어오는 인자는 Read-Only인 MutationRecord의 배열로, 다음과 같은 속성을 가진다.

  • addedNodes
  • attributeName
  • attributeNamespace
  • nextSibling
  • oldValue
  • previousSibling
  • removedNodes
  • target
  • type

Web API를 잘 살펴보면 편리한 기능들이 이미 구현되어 있음을 알 수 있다. 굳이 라이브러리를 쓰지 않아도 web native api만을 사용해서 구현이 쉽게 가능하다는 이야기다.

React에서는 state의 변화로 하위 dom을 렌더링하는 것은 용이하나, 하위 dom의 변화로 state를 변경하는 것은 쉽지 않다.

이럴 경우에 MutationObserver를 두어 dom이 변경되었을 때 → state를 변화하도록 하면 좋을 것 같다.

물론, 이런 경우에는 cycle이 생기지 않도록 각별히 유의해야 한다!!