UNPKG

@mornya/react-image-libs

Version:
65 lines (64 loc) 2.99 kB
var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; export var ImageObserver; (function (ImageObserver) { var Provider = (function () { function Provider(option) { this.subscribe = this.subscribe.bind(this); this.subscribeOnce = this.subscribeOnce.bind(this); this.unsubscribe = this.unsubscribe.bind(this); this.destroy = this.destroy.bind(this); var observerOption = __assign({ root: null, rootMargin: '0px 0px 0px 0px', threshold: 0 }, option); this.intersectionObserver = new IntersectionObserver(function (entries, observer) { entries.forEach(function (entry) { if (entry.isIntersecting) { observer.unobserve(entry.target); entry.target.dispatchEvent(new CustomEvent('imageObserverIntersecting', { detail: __assign(__assign({}, entry), { unsubscribe: function () { observer.unobserve(entry.target); } }), })); } }); }, observerOption); } Provider.prototype.subscribe = function (target, subscribeCallback) { var callbackHandler = function (event) { return subscribeCallback(event); }; target.addEventListener('imageObserverIntersecting', callbackHandler, false); this.intersectionObserver.observe(target); return function () { target.removeEventListener('imageObserverIntersecting', callbackHandler); }; }; Provider.prototype.subscribeOnce = function (target, subscribeCallback) { var _this = this; var callbackHandler = function (event) { _this.unsubscribe(target); return subscribeCallback(event); }; target.addEventListener('imageObserverIntersecting', callbackHandler, { once: true, capture: false }); this.intersectionObserver.observe(target); }; Provider.prototype.unsubscribe = function (target) { this.intersectionObserver.unobserve(target); }; Provider.prototype.destroy = function () { var _this = this; this.intersectionObserver.takeRecords().forEach(function (entry) { return _this.intersectionObserver.unobserve(entry.target); }); this.intersectionObserver.disconnect(); }; return Provider; }()); ImageObserver.Provider = Provider; })(ImageObserver || (ImageObserver = {}));