Reputation: 1485
using resizeObserver, i'm trying to update the data in Alpine.js to display it in the app. Currently it displays the data once but not when the window is resized. Codpen
Code below
function app() {
return {
init() {
var ro = new ResizeObserver((entries) => {
for (let entry of entries) {
console.log(entry);
this.dimensions.push({
dim: `${(entry.contentRect.width / 16).toFixed(2)}rem`
});
}
});
ro.observe(this.$refs.box);
ro.observe(document.documentElement);
},
dimensions: [],
display: []
};
}
html
<div class="color"></div>
<div class="wrapper" x-data="app()">
<p class="dimension" x-text="dimensions[1].dim"></p>
<div class="box">
<p class="dimension" x-text="dimensions[0].dim" x-ref="box"></p>
<pre class="code">margin-inline: max(0px,((100% - 64rem) / 2))</pre>
</div>
</div>
Upvotes: 0
Views: 471
Reputation: 3834
Since you're adding the observed entry to the end of an array. You would have to x-text
on that last entry too, meaning your code should look something like this:
<div class="color"></div>
<div class="wrapper" x-data="app()">
<p class="dimension" x-text="dimensions[dimensions.length - 1].dim"></p>
<div class="box">
<p class="dimension" x-text="dimensions[dimensions.length - 1].dim" x-ref="box"></p>
<pre class="code">margin-inline: max(0px,((100% - 64rem) / 2))</pre>
</div>
</div>
Or you should just make the dimension
variable a simple single entry, and override that when something new is observed.
Upvotes: 1