Ok so sometimes you need typescript for your hooks.
And then basically you need to type every single method in the hook.
You have to do bindings in mounted so that you could use the functions in callbacks and so fortt.
It becomes really tiring and verbose really quickly.
Solution?
LiveViewHook class
Here's a simple example of how to use it:
import { LiveViewHook } from './live_view_hook'
class HeightTrackerHook extends LiveViewHook {
private resizeObserver: ResizeObserver | null = null
mounted() {
this.resizeObserver = new ResizeObserver(this.setHeightProperty)
this.resizeObserver.observe(this.el)
}
beforeDestroy() {
this.resizeObserver?.unobserve(this.el)
}
private setHeightProperty = ([entry]: ResizeObserverEntry[]) => {
document.documentElement.style.setProperty(this.requiredAttr('data-height-var'), `${entry.contentRect.height}px`)
}
}
export default HeightTrackerHook.createViewHook()
Hope this helps!
Take care!