Home

2 minute read

Setting Alpine Data Outside of the Component

Tony Lea

Setting Alpine Data Outside of the Component

Using the new AlpineJS event system in version 3.0 we can easily set data from outside the component by using custom events.

I had previously written an article where I showed you how to get and set data outside of the AlpineJS component scope using the .__x property; however, this is only accessible in version 2 so I wanted to explain how you can implement this type of functionality in v3. Let's dive into it.

Alpine Custom Events

In Alpine v3 you can now add custom events to any component, like so:

<div x-data="{ open: false }" @open-me="open=true">
    <div @click="open=true">Open Me</div>
    <div x-show="open">I've been opened</div>
</div>

As you can see above we've added a custom even called open-me. You can use this custom event inside of the component like so:

<div x-data="{ open: false }" @open-me="open=true">
    <div @click="$dispatch('open-me')">Open Me</div>
    <div x-show="open">I've been opened</div>
</div>

Here is a quick codepen of this simple functionality:

That's pretty simple, right? But, what if we want to call that event from outside of our component.

Alpine Custom Event Outside of Component

If we wanted to call our custom event from outside of our component we can easily attach .window to the end of our event to expose it to the global window, like so:

<div x-data="{ open: false }" @open-me.window="open=true">
    <div @click="$dispatch('open-me')">Open Me</div>
    <div x-show="open">I've been opened</div>
</div>
<button x-data @click="$dispatch('open-me')">
    Open from Outside the Component
</button>

Here is a codepen example of this functionality 👇

You can see that we are now able to call this custom event from outside the scope of the component. Hazah 🎉.

Referencing a Specific Component Event

Lastly, what if this component was inside a loop and we wanted to call one specific component and fire the custom event for that specific component? Easy enough we can fire off a custom event for that element, like so:

<div id="component-1" x-data="{ open: false }" @open-me="open=true">
    <div @click="$dispatch('open-me')">Open Me</div>
    <div x-show="open">I've been opened</div>
</div>
<button onclick="document.getElementById('component-1').dispatchEvent(new CustomEvent('open-me', { detail: {}}));">
    Open from Outside the Component
</button>

As you can see AlpineJS is simply triggering the native javascript custom events, it's just providing a wrapper around a lot of this functionality and making it easier to work with.

Here is another example codepen of this custom event functionality below:

Conclusion

That's the basics of calling events from outside of the component scope in Alpine. Be sure to head over to the official Alpine docs to learn more.

Hope this tutorial helped you understand a little more about Alpine, and I hope you have an awesome day 😉