UNPKG

@studiometa/js-toolkit

Version:

A set of useful little bits of JavaScript to boost your project! 🚀

69 lines (68 loc) • 1.62 kB
function withMountWhenInView(BaseClass, defaultOptions = { threshold: [0, 1] }) { class WithMountWhenInView extends BaseClass { /** * Config. */ static config = { ...BaseClass.config, options: { intersectionObserver: Object } }; /** * Is the component visible? * * @private */ __isVisible = false; /** * The component's observer. * * @private */ __observer; /** * Create an observer when the class in instantiated. * * @param {HTMLElement} element The component's root element. */ constructor(element) { super(element); this.__observer = new IntersectionObserver( (entries) => { const isVisible = entries.reduce((acc, entry) => acc || entry.isIntersecting, false); if (this.__isVisible !== isVisible) { this.__isVisible = isVisible; if (isVisible) { this.$mount(); } else { setTimeout(() => this.$destroy()); } } }, { ...defaultOptions, ...this.$options.intersectionObserver } ); this.__observer.observe(this.$el); this.$on("terminated", () => { this.__observer.disconnect(); }); } /** * Override the mounting of the component. */ async $mount() { if (this.__isVisible) { return super.$mount(); } return this; } } return WithMountWhenInView; } export { withMountWhenInView }; //# sourceMappingURL=withMountWhenInView.js.map