Hej, mam problem z podpięciem EventListenera uruchamiającego funkcję z danej klasy.
Założenie jest takie aby funkcja bodyPadding() wywoływała się na init() - to działa, a następnie każdorazowo podczas zdarzenia 'resize' dla window.
Mój kod:
1.plik z funkcją
import scrollMonitor from 'scrollmonitor';
export default class StickyHeader {
constructor () {
this.selector = '.js-site-header';
this.elements = '.js-sticky';
this.stickyClass = 'sticky';
this.init();
}
init () {
this.stickyHeader = document.querySelector(this.selector);
this.stickyElements = document.querySelectorAll(this.elements);
if (! this.stickyHeader ) {
return;
}
this.bodyPadding();
this.secondWatcher = scrollMonitor.create(this.stickyHeader, 50);
this.secondWatcher.lock();
this.secondWatcher.enterViewport(() => this.stickyRemove());
this.secondWatcher.exitViewport(() => this.stickyAdd());
}
stickyAdd () {
for(let i = 0; i < this.stickyElements.length; i++) {
this.stickyElements[i].classList.add(this.stickyClass)
}
}
stickyRemove () {
for(let i = 0; i < this.stickyElements.length; i++) {
this.stickyElements[i].classList.remove(this.stickyClass)
}
}
bodyPadding() {
this.headerHeight = this.stickyHeader.clientHeight;
console.log('headerHeight' + this.headerHeight);
document.body.style.paddingTop = this.headerHeight + 'px';
}
}
- plik z wywołaniem
import StickyHeader from '../components/sticky-menu';
export default {
init() {
// JavaScript to be fired on all pages
const stickyHead = new StickyHeader;
window.addEventListener('resize', stickyHead.bodyPadding);
},
finalize() {
// JavaScript to be fired on all pages, after page specific JS is fired
},
};
Podczas 'resize' okna przeglądarki w konsoli mam błąd
Uncaught TypeError: Cannot read property 'clientHeight' of undefined at bodyPadding (sticky-menu.js:41)
nie mogę wywołać też z konsoli ani zmiennej do której przypisałem klasę ani samej klasy.
StickyHeader()
VM871:1 Uncaught ReferenceError: StickyHeader is not defined
at <anonymous>1
(anonymous) @ VM871:1
StickyHeader
VM883:1 Uncaught ReferenceError: StickyHeader is not defined
at <anonymous>1
(anonymous) @ VM883:1
stickyHead
VM909:1 Uncaught ReferenceError: stickyHead is not defined
at <anonymous>1
Wygląda na to, że po przypisaniu klasy i wywołaniu constructora tracę dostęp do zmiennej.
Jak temu zapobiec? Jak prawidłowo to wywołać? A najlepiej - w jaki sposób dodać taki eventlistener bezpośrednio do klasy?
Próbowałem dodać evenlistenera do init, ale nie działał.
Z góry dzięki!