Store @click handlers do not work when function is not invoked in attribute #4380
-
We encountered an issue where the DOM does not update as expected when omitting parentheses in the @click attribute. Working Example:The following code works as expected: <!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
</head>
<body>
<button x-data @click="$store.someStore.toggle()" :class="$store.someStore.show && 'bg-black'">
<span x-text="$store.someStore.show"></span>
</button>
<script>
document.addEventListener('alpine:init', () => {
Alpine.store('someStore', {
show: false,
toggle() {
this.show = !this.show;
console.log('Toggle | Show: ', this.show);
}
});
});
</script>
</body>
</html> Failing Example:In this variation, the DOM does not update, even though the <!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
</head>
<body>
<button x-data @click="$store.someStore.toggle" :class="$store.someStore.show && 'bg-black'">
<span x-text="$store.someStore.show"></span>
</button>
<script>
document.addEventListener('alpine:init', () => {
Alpine.store('someStore', {
show: false,
toggle() {
this.show = !this.show;
console.log('Toggle | Show: ', this.show);
}
});
});
</script>
</body>
</html> Issue:The key difference between the two examples is the function invocation in the
In both cases, Expected Behavior:Based on the documentation here, it is shown that the parentheses Conclusion:This seems like a bug with AlpineJS. Even though the References: |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
When leaving out This is a known and expected behavior. We should probably make it more clear in the documentation that with |
Beta Was this translation helpful? Give feedback.
When leaving out
()
the method is run with the current context as thethis
instead of the object the method is on. This is true for Stores as well as just nested objects.This is a known and expected behavior. We should probably make it more clear in the documentation that with
()
and without is NOT universally equal.