I am learning ES6 at the moment and I can't wrap my head around this. I call my plugin like this:
var fnLazy = new lazyloadImages();
fnLazy.initializeEvents();
If someone types "fnLazy" inside the webdeveloper toolbar I want to hide "this.lazyloadOnScroll" because it is not relevant. How can I add the function for the eventlisteners outside the class while "this" is still refering to the Class?
((root, factory) => {
var plugin = "lazyloadImages";
if (typeof define === "function" && define.amd) {
define([], factory);
} else if (typeof exports === "object") {
module.exports = factory(plugin);
} else {
root[plugin] = factory(plugin);
}
})(window, (plugin) => {
'use strict';
/* show lazy loadng images when appear in the viewport while scrolling */
function fnDebounce() {
console.log('debouncing');
const that = this;
this.removeIndex = [];
this.lazyImages.forEach((item, i) => {
if (pixieLib.inViewport(item, {percentVisible: that.config.threshold})) {
if (item.hasAttribute('data-srcset')) {
item.srcset = item.dataset.srcset;
}
item.src = item.dataset.src;
item.classList.add('lazy-loaded');
that.removeIndex.push(i);
}
});
for (let i = this.removeIndex.length, item; i > 0; i--) {
item = this.removeIndex[i - 1];
this.lazyImages.splice(item, 1);
}
if (!this.lazyImages.length) {
console.log('removeEventListeners');
this.destroyEvents();
}
}
function extend(src, props) {
for (let prop in props) {
if (props.hasOwnProperty(prop)) {
let val = props[prop];
if (val && Object.prototype.toString.call(val) === "[object Object]") {
src[prop] = src[prop] || {};
extend(src[prop], val);
} else {
src[prop] = val;
}
}
}
return src;
}
class lazyloadImages {
constructor(config) {
const defaultConfig = {
className : '.js-lazyload-img',
threshold : -100
};
this.config = config ? extend(defaultConfig, config) : defaultConfig;
this.lazyloadOnScroll = _.debounce(fnDebounce.apply(this), 100);
this.lazyImages = Array.prototype.slice.call(document.querySelectorAll(this.config.className));
this.removeIndex;
}
destroyEvents() {
window.removeEventListener('scroll', this.lazyloadOnScroll);
window.removeEventListener('resize', this.lazyloadOnScroll);
window.removeEventListener('load', this.lazyloadOnScroll);
}
initializeEvents() {
window.addEventListener('scroll', this.lazyloadOnScroll.bind(this));
window.addEventListener('resize', this.lazyloadOnScroll.bind(this));
window.addEventListener('load', this.lazyloadOnScroll.bind(this));
}
get reinit(){
this.destroyEvents();
this.lazyImages = Array.prototype.slice.call(document.querySelectorAll(`${this.config.className}:not(.lazyloaded)`));
this.initializeEvents();
}
}
return lazyloadImages;
});