본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

뮤테이션 옵저버 (Mutation Observer)

원문 보기 위키 갱신

브라우저의 MutationObserver API를 얇고 선언적인 인터페이스로 감싼 컴포넌트예요. 감싼 콘텐츠의 변화를 sl-mutation 이벤트로 알려줘요. 이벤트가 발생하면 어떻게 변했는지에 대한 정보를 담은 MutationRecord 객체 컬렉션이 event.detail에 붙어요. _ | SlMutationObserver, Shoelace 2.0부터 제공되고 있으며 stable 상태예요.

출처: 문서

본문

| SlMutationObserver — Since 2.0, stable

Mutation Observer 컴포넌트는 MutationObserver API에 대한 얇고 선언적인 인터페이스를 제공해요.

뮤테이션 옵저버는 자신이 감싼 콘텐츠의 변화를 sl-mutation 이벤트로 보고해요. 이벤트가 발생하면, 어떻게 변했는지에 대한 정보를 담은 MutationRecord 객체 컬렉션이 event.detail에 붙어요.

<div class="mutation-overview">
  <sl-mutation-observer attr="variant">
    <sl-button variant="primary">Click to mutate</sl-button>
  </sl-mutation-observer>
  <br />
  👆 Click the button and watch the console
  <script>
    const container = document.querySelector('.mutation-overview');
    const mutationObserver = container.querySelector('sl-mutation-observer');
    const button = container.querySelector('sl-button');
    const variants = ['primary', 'success', 'neutral', 'warning', 'danger'];
    let clicks = 0;
    // Change the button's variant attribute
    button.addEventListener('click', () => {
      clicks++;
      button.setAttribute('variant', variants[clicks % variants.length]);
    });
    // Log mutations
    mutationObserver.addEventListener('sl-mutation', event => {
      console.log(event.detail);
    });
  </script>
  <style>
    .mutation-overview sl-button {
      margin-bottom: 1rem;
    }
  </style>
</div>
import { useState } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlMutationObserver from '@shoelace-style/shoelace/dist/react/mutation-observer';
const css = `
  .resize-observer-overview div {
    display: flex;
    border: solid 2px var(--sl-input-border-color);
    align-items: center;
    justify-content: center;
    text-align: center;
    padding: 4rem 2rem;
  }
`;
const variants = ['primary', 'success', 'neutral', 'warning', 'danger'];
let clicks = 0;
const App = () => {
  const [variant, setVariant] = useState('primary');
  function handleClick() {
    clicks++;
    setVariant(variants[clicks % variants.length]);
  }
  return (
    <>
      <SlMutationObserver attr="*" onSlMutation={event => console.log(event.detail)}>
        <SlButton variant={variant} onClick={handleClick}>
          Click to mutate
        </SlButton>
      </SlMutationObserver>
      <style>{css}</style>
    </>
  );
};

뮤테이션 옵저버를 만들 때는 attr, child-list, char-data 중 적어도 하나를 포함해 어떤 변화에 반응할지 지정해야 해요. 이 속성 중 하나라도 지정하지 않으면 뮤테이션 이벤트가 발생하지 않아요.

Examples

Child List

child-list 속성을 쓰면 추가되거나 제거되는 새 자식 요소들을 감시할 수 있어요.

<div class="mutation-child-list">
  <sl-mutation-observer child-list>
    <div class="buttons">
      <sl-button variant="primary">Add button</sl-button>
    </div>
  </sl-mutation-observer>
  👆 Add and remove buttons and watch the console
  <script>
    const container = document.querySelector('.mutation-child-list');
    const mutationObserver = container.querySelector('sl-mutation-observer');
    const buttons = container.querySelector('.buttons');
    const button = container.querySelector('sl-button[variant="primary"]');
    let i = 0;
    // Add a button
    button.addEventListener('click', () => {
      const button = document.createElement('sl-button');
      button.textContent = ++i;
      buttons.append(button);
    });
    // Remove a button
    buttons.addEventListener('click', event => {
      const target = event.target.closest('sl-button:not([variant="primary"])');
      event.stopPropagation();
      if (target) {
        target.remove();
      }
    });
    // Log mutations
    mutationObserver.addEventListener('sl-mutation', event => {
      console.log(event.detail);
    });
  </script>
  <style>
    .mutation-child-list .buttons {
      display: flex;
      gap: 0.25rem;
      flex-wrap: wrap;
      margin-bottom: 1rem;
    }
  </style>
</div>
import { useState } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlMutationObserver from '@shoelace-style/shoelace/dist/react/mutation-observer';
const css = `
  .mutation-child-list .buttons {
    display: flex;
    gap: .25rem;
    flex-wrap: wrap;
    margin-bottom: 1rem;
  }
`;
let buttonCount = 0;
const App = () => {
  const [buttonIds, setButtonIds] = useState([]);
  function addButton() {
    setButtonIds([...buttonIds, ++buttonCount]);
  }
  function removeButton(id) {
    setButtonIds(buttonIds.filter(i => i !== id));
  }
  return (
    <>
      <div className="mutation-child-list">
        <SlMutationObserver child-list onSlMutation={event => console.log(event.detail)}>
          <div className="buttons">
            <SlButton variant="primary" onClick={addButton}>
              Add button
            </SlButton>
            {buttonIds.map(id => (
              <SlButton key={id} variant="default" onClick={() => removeButton(id)}>
                {id}
              </SlButton>
            ))}
          </div>
        </SlMutationObserver>
      </div>
      👆 Add and remove buttons and watch the console
      <style>{css}</style>
    </>
  );
};

Importing

autoloader나 전통적인 loader를 사용하고 있다면 이 부분은 건너뛰어도 돼요. 그 외에는 아래 스니펫 중 원하는 걸 골라 이 컴포넌트만 골라 가져올 수 있어요.

Script / Import / Bundler / React 방식이 준비되어 있어요.

CDN에서 <script> 태그로 이 컴포넌트를 가져오려면:

<script type="module" src="https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.20.1/cdn/components/mutation-observer/mutation-observer.js"></script>

CDN에서 JavaScript import로 가져오려면:

import 'https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.20.1/cdn/components/mutation-observer/mutation-observer.js';

Bundler를 사용해 가져오려면:

import '@shoelace-style/shoelace/dist/components/mutation-observer/mutation-observer.js';

React 컴포넌트로 가져오려면:

import SlMutationObserver from '@shoelace-style/shoelace/dist/react/mutation-observer';

Slots

Name Description
(default) The content to watch for mutations.

슬롯 사용법에 대해 더 알아보세요.

Properties

Name Description Reflects Type Default
attr Watches for changes to attributes. To watch only specific attributes, separate them by a space, e.g.
attr="class id title". To watch all attributes, use *. string -
attrOldValue
attr-old-value Indicates whether or not the attribute’s previous value should be recorded when monitoring changes. boolean false
charData
char-data Watches for changes to the character data contained within the node. boolean false
charDataOldValue
char-data-old-value Indicates whether or not the previous value of the node’s text should be recorded. boolean false
childList
child-list Watches for the addition or removal of new child nodes. boolean false
disabled Disables the observer. boolean false
updateComplete A read-only promise that resolves when the component has
finished updating.

속성과 프로퍼티에 대해 더 알아보세요.

Events

Name React Event Description Event Detail
sl-mutation onSlMutation Emitted when a mutation occurs. { mutationList: MutationRecord[] }

이벤트에 대해 더 알아보세요.

더 알아보기 (Learn more)