CBWIRE Feature Preview: Dispatch Browser Events

In CBWIRE, we’ve had the ability for some time to emit events from one component to another. These were internal to CBWIRE though, so you had to define a listener in another CBWIRE component.

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

// wires/MyComponent.cfm
<cfscript>
    data = {};

    function submitForm(){
        // Dispatch a 'form-submitted' browser event. Pass parameters
        dispatch( "form-submitted", { "submittedBy": "Grant" } );
    }
</cfscript>

<cfoutput>
    <div>
        <form wire:submit.prevent="submitForm">
            <button type="submit">Dispatch event</button>
        </form>
    </div>
</cfoutput>

Now we can listen for that event in vanilla JS elsewhere in our application.

<script>
window.addEventListener('form-submitted', event => {
    alert('Form submitted by: ' + event.detail.submittedBy);
} )
</script>

If we are using AlpineJS, we can listen for the event like this.

<div x-data="{ show: false }" @form-submitted.window="show = true">
    <div x-show="true">
        Form was submitted.
    </div>
</div>

This feature will be included in the upcoming 3.2 release of CBWIRE. If you want to experiment with it now, just pull down the latest bleeding edge version using CommandBox.

box install cbwire@be --force

Enjoy! :peace_symbol:

6 Likes