웹 컴포넌트란 컴포넌트의 기능을 다른 코드로부터 캡슐화하여 재사용 가능한 custom element를 생성하고 웹 앱에서 활용할 수 있도록 해주는 다양한 기술들의 모음입니다.
<iframe>
을 통해서 스코프를 독립적으로 관리할 수 있었지만, 최선은 아니였음.<div>
대신 <current-time>
처럼 적절한 이름의 태그를 사용할 수 있다class MyComponent extends HTMLElement {...}
// html의 <my-component>태그에 MyComponent 클래스를 정의
customElements.define("my-component", MyComponent);
class MyComponent extends HTMLElement {
// element 생성시
constructor() {
super();
...
}
// element가 document에 추가될 때 브라우저가 이 메서드를 호출합니다.
// element가 추가/제거될 때마다 반복적으로 호출합니다.
connectedCallback() {
...
}
// element가 document에서 제거될 때 브라우저가 이 메서드를 호출합니다.
// 마찬가지로 element가 추가/제거될 때마다 반복적으로 호출합니다.
disconnectedCallback() {
...
}
// 변경을 감지할 attribute들을 모니터링하기 위한 메서드입니다.
static get observedAttributes() {
return [...];
}
// 위에서 모니터링중인 attribute가 변경되었을 때, 호출됩니다.
attributeChangedCallback(name, oldValue, newValue) {
...
}
// element가 새로운 document로 움직였을때 호출합니다.
adoptedCallback() {
...
}
// 그외의 다른 Property나 메서드 존재..
}
class MyComponent extends HTMLElement {
// element가 문서에 추가되었을 때, 브라우저가 이 메서드를 호출함
connectedCallback() {
// mode속성은 캡슐화 레벨을 설정하며, open은 코드로 접근할 수 있고, closed는 항상 elem.shadowRoot의 값이 null이다.
this.attachShadow({ mode: 'open' });
}
}
Web Components - Keep calm and UseThePlatform