EventListeners

Web API 중 하나인 CustomEvent에 대한 함수입니다.

Copy Code

utils/event-listener.ts
class EventListenerGenerator {
  add(type: string, listener: EventListenerOrEventListenerObject) {
    window.addEventListener(type, listener)
  }
  remove(type: string, listener: EventListenerOrEventListenerObject) {
    window.removeEventListener(type, listener)
  }
  once(type: string, listener: any) {
    const emitOnce = (event: any) => {
      listener(event)
      this.remove(type, emitOnce)
    }
 
    this.add(type, emitOnce)
  }
  emit<T>(type: string, detail?: T) {
    const event = new CustomEvent<T>(type, { detail })
    window.dispatchEvent(event)
  }
}
 
export const EventListener = new EventListenerGenerator()

Usage

const onBackdrop = useCallback(
  ({ detail }: any) => {
    setIsOpen(detail)
    if (detail) document.body.style.overflow = 'hidden'
    else document.body.removeAttribute('style')
  },
  [isOpen]
)
 
useEffect(() => {
  EventListener.add('backdrop', onBackdrop)
  return () => EventListener.remove('backdrop', onBackdrop)
}, [])
 
<button onClick={() => EventListener.emit('backdrop', true)}>Backdrop</button>

References