06. Javascript/기초

18. 자바스크립트 (JavaScript) - WebComponent

THE HEYDAZE 2021. 10. 1. 21:22

 

삭제 시 이벤트를 달았기 때문에 동작하는 것이다

 

깃허브는 리액트를 쓰지않고 WebComponent 를 이용하여 만들어졌다고 합니다
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        class CustomEle extends HTMLElement { // 생성자 에서는 보통 해당 엘리먼트에 포함된 함수를 초기화 한다. 
            constructor() { super(); } // 커스텀 엘리먼트가 생성될때 실행된다. 
            connectedCallback() { this.render(); } // 해당요소가 새로운 문서로 이동 될 때마다 호출 된다. 
            adoptCallback() { } // 요소의 속성이 추가, 제거, 업데이트, 교체되는 부분을 관찰하고 호출된다. 
            // 이때 observedAttributes 속성에 나열된 특성에서만 호출된다.
            attributeChangedCallback(attrName, oldVal, newVal) {
                this.render();
            } //attributeChangedCallback 에서 관찰하는 항목을 리턴한다.
            static get observedAttributes() { return ['title']; }
            get title() { return this.getAttribute('title'); } // custom element 가 제거될때 호출된다. 
            disconnectedCallback() { alert('bye bye'); } // custom method
            render() { this.innerHTML = ` <h1>${this.title}</h1> ` }
        }
        window.customElements.define('custom-ele', CustomEle);


    </script>

    <custom-ele id='test' title="Hello World"></custom-ele>

    <button type="button" onclick="document.getElementById('test').remove()">삭제</button>
</body>

</html>