이번 글에서는 DOM 인터페이스와 비슷한 EventTarget 클래스를 만들어보려고 한다.
해당 클래스로 이벤트 리스너들을 지속적으로 트랙킹이 가능하며, event를 dispatch하여 원할때 실행도 가능하다.
class EventTarget { // 등록한 이벤트들을 관리할 listeners 객체 constructor() { this.listeners = {}; } // 이벤트 이름과 실행시킬 콜백함수를 인자로 받아서 // listeners 프로퍼티에 등록 addEventListener(name, callback) { // 처음 등록되는 이벤트라면 Set 생성자를 사용하여 초기값 셋팅 if(!this.listeners.hasOwnProperty(name)) { this.listeners[name] = new Set([callback]); } else { this.listeners[name].add(callback); } } // name과 add했던 같은 콜백함수를 넣어 원하는 이벤트 삭제 removeEventListener(name, callback) { this.listeners[name].delete(callback); } // 등록된 name의 이벤트가 있다면 루프를 돌아 모든 콜백함수 실행 dispatchEvent(name) { if(!this.listeners[name]) return; for(const callback of this.listeners[name]) { callback(); } } }