'How to force AlpineJS method results to update?
How do I force AlpineJS to reevaluate all methods?
Background: I have a caroussel consisting of a flexibly sized container and its content. When the horizontal space needed for the content exceeds the container width, I show buttons for the user to navigate left and right through the content. The button visibility is (simplified) handled like this:
<div x-ref="mask">
<ul x-ref="container">
<button x-show="!contentFits()">
<li>{{ contentA }}</li>
<li>{{ contentB }}</li>
</ul>
</div>
contentFits(){
return this.contentWidth() - 1 <= this.$refs.mask.getBoundingClientRect().width
}
contentWidth(){
let width = new Number
for (let item of this.$refs.container.children) {
width = width + item.getBoundingClientRect().width
}
return width;
}
The mask and container have a width relative to the viewport width. So when the viewport is resized, contentWidth() needs to be reevaluated.
I now solve this rather inelegantly by adding a watcher and a small modification to contentFits():
init(){
window.addEventListener('resize', ()=>{ this.inelegantProperty++ });
},
contentFitsInsideScrollContainer(){
return this.inelegantProperty - this.inelegantProperty + this.contentWidth() - 1 <= this.$refs.mask.getBoundingClientRect().width; // Pixel rounding errors require the check with -1 instead of 0.
},
Surely there's something built-in to Alpine to do this in a cleaner way?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
