붉은거위 노트 (redgoose note)

Unique Custom Event

Nest
Development
Category
Javascript
Hit
354
Star
0

window 같이 전역에서 사용하는 이벤트를 여러군데에서 추가하면 서로 중복되어서 꼬여버린다.
그래서 독립적으로 사용하고 관리하고 싶을때 사용할 수 있는 방법이다.

/**
 * initial custom event
 * 중복되는 `dom`에다 여러 이벤트를 넣고 싶을때(특히 window) 유니크한 이름으로 이벤트를 만들 수 있도록 커스텀 이벤트를 만들어서 사용할때 사용한다.
 * https://gist.github.com/yairEO/cb60592476a4204b27e83048949dbb45
 */
export function initCustomEvent()
{
  const events = {
    on(event, cb, opts)
    {
      if (!this.namespaces) this.namespaces = {};
      // 중복된 이벤트가 설정한다면 이전 이벤트를 삭제한다.
      if (this.namespaces[event]) this.off(event);
      this.namespaces[event] = cb;
      const options = opts || false;
      this.addEventListener(event.split('.')[0], cb, options);
      return this;
    },
    off(event)
    {
      if (!this.namespaces[event]) return;
      this.removeEventListener(event.split('.')[0], this.namespaces[event]);
      delete this.namespaces[event];
      return this;
    },
  };
  window.on = document.on = Element.prototype.on = events.on;
  window.off = document.off = Element.prototype.off = events.off;
}

이와같은 함수를 먼저 실행하고 다음과 같이 on()메서드를 사용하여 이벤트를 추가합니다.

window.on('click.foo', () => { console.log('click.foo'); });
window.on('click.bar', () => { console.log('click.bar'); });

이벤트를 삭제하려면 다음과 같이 off()메서드를 사용합니다.

window.off('click.foo');
window.off('click.bar');

전역에서 키보드나 윈도우 리사이즈, 스크롤같은 일을 사용하는 이벤트를 사용할때 이 도구가 많은 도움이 되어서 항상 사용하곤 한다.