Output:
x-init: Calling $dispatch
x-init: Called $dispatch
<div x-data="page()" x-init="init($dispatch)" class="block w-full" > <p class="block"> Output: <br> <code x-text="output" > x-init: Calling $dispatch x-init: Called $dispatch</code> </p> <button @click="handleClick($event, $dispatch)" class="mt-4 w-2/3 justify-center flex bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" value="button-value" > Get $event and $dispatch on click </button> <script type="text/javascript"> function page() { return { output: "", init($dispatch) { // $dispatch is **not** defined in x-init handler this.output += "x-init: Calling $dispatch"; $dispatch("test"); this.output += "\nx-init: Called $dispatch"; }, handleClick(e, $dispatch) { this.output += `\nx-on: event.target.value: "${e.target.value}"`; this.output += "\nx-on: Calling $dispatch"; $dispatch("test2"); this.output += "\nx-on: Called $dispatch"; }, }; } </script> </div>
💥 Subscribe for Early Access to the Alpine.js Handbook 📖 💥