Skip to content

Instantly share code, notes, and snippets.

@cahilfoley
Last active June 14, 2019 13:31
Show Gist options
  • Save cahilfoley/849805a6e0c4e3d71619f278e495f105 to your computer and use it in GitHub Desktop.
Save cahilfoley/849805a6e0c4e3d71619f278e495f105 to your computer and use it in GitHub Desktop.
[Browser Utilities] Random utility functions that are useful when working in the browser #browser
/**
* Gets the height and width of the provided HTML element
* @param element The html element to measure
*/
export function getSize(element?: HTMLElement) {
if (!element) return { height: 0, width: 0 }
return {
height: element.offsetHeight,
width: element.offsetWidth,
}
}
type EventHandler<E extends keyof DocumentEventMap> = (event: DocumentEventMap[E]) => void
export class SharedEventListener<E extends keyof DocumentEventMap> {
private subscribers: EventHandler<E>[]
public readonly target: HTMLElement
public readonly event: E
constructor(event: E, target = document.documentElement) {
this.event = event
this.target = target
this.subscribers = []
}
private attach = () => {
this.target.addEventListener(this.event, this.handleEvent)
}
private detach = () => {
this.target.removeEventListener(this.event, this.handleEvent)
}
private handleEvent = (event: DocumentEventMap[E]) => {
this.subscribers.forEach(listener => listener(event))
}
public subscribe = (handler: EventHandler<E>) => {
if (this.subscribers.length === 0) {
this.attach()
}
this.subscribers.push(handler)
return () => this.unsubscribe(handler)
}
public unsubscribe = (handler: EventHandler<E>) => {
this.subscribers = this.subscribers.filter(listener => listener !== handler)
if (this.subscribers.length === 0) {
this.detach()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment