I have a Vue-structure like this:
App
|--{ data: { scrollInfo {...} } }
|
|--Component1
| |--{ data: { sidebarWidth: 500 }
|
|--Component2
| |--{ data: { overlayItemWidth: 389 }
|
|--Component3
...
...
In each of my components, I have elements that has variables that should change on scroll and resize (such as sidebarWidth
or overlayItemWidth
). I found this post here that shows this way of adding a listener for scroll and resize.
I've added it to the main instance, like so:
data: {
scrollInfo: {
scrollFromTop: 0,
viewportHeight: 0,
viewportWidth: 0,
pageHeight: 0
}
},
created() {
window.addEventListener( 'scroll', this.calculateScroll );
window.addEventListener( 'resize', this.calculateViewport );
window.addEventListener( 'resize', this.calculatePageScrollSpecs );
this.calculateViewport();
this.calculateScroll();
this.calculatePageScrollSpecs();
},
destroyed() {
window.removeEventListener( 'scroll', this.calculateScroll );
window.removeEventListener( 'resize', this.calculateViewport );
window.removeEventListener( 'resize', this.calculatePageScrollSpecs );
}
I wont show the contents of the methods (calculateScroll
, calculateViewport
, ... ), since it's not relevant to this question.
Now... In my components I have variables that should change and reevaluate on scroll and on resize as well. But every time I have such a variable, then I currently add those same listeners in created
and destroyed
, and then add the same event-listeners to the given component, and then do the calculations from a new method in there. It seems long and clumbsy.
Are there a way that I can get around having those window.AddEventListener
s in each component, but only have those in my root instance?
... I was thinking, if I had an array of 'things-that-need-to-be-recalculated-on-scroll-or-resize' in my main instance, but I'm not sure if it would get cluttered, since the variables for the components then actually wouldn't be kept in the component, but instead be referenced with this.$root.sidebarWidth
. And this would also make my main instance massive.
Any suggestions?