Events

Events and listeners provide an elegant means for your components to communicate. You can dispatch events from one component, listen for them on another, execute actions, and re-render the listener.

Dispatching Events

You can dispatch events directly in your component actions using dispatch().

// ./wires/Posts.bx
class extends="cbwire.models.Component" {
    function addPost() {
        dispatch( "post-added" );
    }
}

You can dispatch events from your templates using $dispatch().

<!--- ./wires/posts.bxm|cfm --->
<div>
    <button wire:click="$dispatch( 'post-added' )">Add Post</button>
</div>

You can also dispatch using the Livewire JavaScript object.

<!--- ./wires/posts.bxm|cfm --->
<script>
    Livewire.dispatch( 'post-added' );
</script>

Passing Parameters

You can send parameters as your dispatching an event.

dispatchTo

You can dispatch events to components of a specific component using dispatchTo().

dispatchSelf

You can dispatch events to the component that fired the event using dispatchSelf().

Listeners

You register event listeners by adding a listeners struct to your component.

Listeners are a key/value pair where the key is the event to listen for, and the value is the action to invoke on the component.

JavaScript keys are case-sensitive. To preserve the key casing in CFML, surround your listener names in quotations.

Dispatching Browser Events

You can also dispatch browser events using the dispatch() method.

You can listen for the event using vanilla JavaScript:

If you use Alpine.js, you can listen for an event like this.

Was this helpful?