SHARE
TWEET

Untitled

a guest Jun 26th, 2019 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. type EventHandler<E extends keyof DocumentEventMap> = (event: DocumentEventMap[E]) => void
  2.  
  3. export class SharedEventListener<E extends keyof DocumentEventMap> {
  4.   private subscribers: EventHandler<E>[]
  5.   public readonly target: HTMLElement
  6.   public readonly event: E
  7.  
  8.   constructor(event: E, target = document.documentElement) {
  9.     this.event = event
  10.     this.target = target
  11.     this.subscribers = []
  12.   }
  13.  
  14.   private attach = () => {
  15.     this.target.addEventListener(this.event, this.handleEvent)
  16.   }
  17.  
  18.   private detach = () => {
  19.     this.target.removeEventListener(this.event, this.handleEvent)
  20.   }
  21.  
  22.   private handleEvent = (event: DocumentEventMap[E]) => {
  23.     this.subscribers.forEach(listener => listener(event))
  24.   }
  25.  
  26.   public subscribe = (handler: EventHandler<E>) => {
  27.     if (this.subscribers.length === 0) {
  28.       this.attach()
  29.     }
  30.  
  31.     this.subscribers.push(handler)
  32.  
  33.     return () => this.unsubscribe(handler)
  34.   }
  35.  
  36.   public unsubscribe = (handler: EventHandler<E>) => {
  37.     this.subscribers = this.subscribers.filter(listener => listener !== handler)
  38.  
  39.     if (this.subscribers.length === 0) {
  40.       this.detach()
  41.     }
  42.   }
  43. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top