I am trying to implement the OOP to manipulate the DOM but there are certain things that I do not know where to place, for example the addEventListeners, a specific case that I am facing is, I have created an object that works with some elements of the DOM and I need to identify the scroll level that the user makes in said object (Menu). One way to do it without the implementation of the OOP is:
//===============================================
//ARCHIVO Menu.JS
//===============================================
exports.Menu = () => {
//Implementación sin OOP
const mainNav = document.getElementById( 'main-nav' );
const features = document.getElementById( 'features-container' );
let lastScrollTop = 0;
const fixMenu = () => {
const currentScroll = window.scrollY;
//darle nuevos estilos al navbar
if ( currentScroll > 0 ) {
mainNav.classList.add( 'is-scrolled' );
} else {
mainNav.classList.remove( 'is-scrolled' );
}
//mostrar u ocultar navbar segun direccion del scroll
if ( currentScroll > lastScrollTop ) {
mainNav.classList.add( 'is-up' );
} else {
mainNav.classList.remove( 'is-up' );
}
lastScrollTop = currentScroll;
};
window.addEventListener( 'scroll', fixMenu );
}
//===============================================
//ARCHIVO Index.JS
//===============================================
import {Menu} from './menu';
const menu = document.getElementById('menu');
const toggler = document.getElementById('toggler');
Menu(menu, toggler);
Now how do I implement the above in OOP, where I place the addEventListeners ?, within the same object? or outside?
//===============================================
//ARCHIVO(objeto) Menu.js
//===============================================
exports.Menu = function ( menu, toggler ) {
const self = this;
function _isDom ( el ) {
return (el !== null && (el.nodeType === 1 || el.nodeType === 11))
? el
: self.error = '[PersaErp] target is null or undefined';
}
self.initialize = () => {
self.menu = _isDom( menu );
self.toggler = _isDom( toggler );
self.initScroll = 0;
self.travelled = 0;
};
self.initialize();
};
//===============================================
//ARCHIVO Index.JS
//===============================================
import {Menu} from './menu';
const menu = document.getElementById('menu');
const toggler = document.getElementById('toggler');
const mainMenu = new Menu(menu, toggler);