> This is part 1 of 3 of the full documentation (pages 1–100 of 204).
> The content is paginated: fetch every part to see all of it.
> Next part: https://cbwire.ortusbooks.com/llms-full.txt/1
> Page index: https://cbwire.ortusbooks.com/llms.txt

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://cbwire.ortusbooks.com/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# Introduction

cbwire is a ColdBox module that makes building reactive, modern apps easy without leaving the comfort of CFML.

![](https://2790241902-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXiNYsHUJlavmFh1GPp%2F-MeKPxS6nCgvYCprGvab%2F-MeKQ0YEFTD_sf2Ioxid%2FcbWire300.png?alt=media\&token=c7d01623-1d56-47a2-b43c-ff869e8265ce)

Building modern apps is complicated. [ColdBox](https://coldbox.ortusbooks.com) makes creating server-side CFML apps easy, but what about the client-side? Front-end JavaScript frameworks like Vue and React are powerful, yet they also introduce complexity and a significant learning curve when creating our apps.

What if you could create apps that look and feel like your Vue and React web apps... but are written with CFML? Impossible, you say? Nay, we say!

Introducing \*\*cbwire: Power-up your CFML!

## Let's create a Counter in cbwire...

Install [CommandBox](https://www.ortussolutions.com/products/commandbox), then from your terminal, run:

```bash
mkdir cbwire-demo
cd cbwire-demo
box coldbox create app .
box install cbwire@be
box server start
```

Let's add cbwire styling and script references to our layout using `wireStyles()` and `wireScripts()`, and include a cbwire component we will create using `wire( "Counter ")`.

```markup
<!--- ./layouts/Main.cfm --->
<cfoutput>
<!doctype html>
<html lang="en">
<head>
    #wireStyles()#
</head>
<body>
    #wire( "Counter" )#
    #wireScripts()#
</body>
</html>
</cfoutput>
```

Let's create our *Counter* cbwire component.

```javascript
// File: ./wires/Counter.cfc
component extends="cbwire.models.Component" {

    // Reactive Data Properties
    variables.data = {
        "counter": "0"
    };

    // Action to increment counter
    function increment(){
        variables.data.counter += 1;
    }
}
```

```markup
<!--- ./views/wires/counter.cfm --->
<cfoutput>
<div>
    <div>Count: #args.counter#</div>
    <button wire:click="increment">
        +
    </button>
</div>
</cfoutput>
```

Now that you've created your *Counter* component, you can include this component in any layout or view throughout your ColdBox app using the `wire()` helper method.

Refresh the page and you find a reactive counter that increments when you hit the plus button.

![](https://2790241902-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXiNYsHUJlavmFh1GPp%2F-MkOc_FXeuijGTPLC217%2F-MkOkPIvkbsjWxVi9pH5%2Fimage.png?alt=media\&token=84a693e1-bac7-45f1-b898-386f30f348bb)

## How is this working!!!?

1. cbwire renders our *Counter* component with our `.cfm` page. ( View Source to see this ). This means cbwire is SEO-friendly.
2. When a user clicks the plus button, cbwire makes an AJAX request to the server and triggers the *increment* action.
3. cbwire updates the counter state
4. cbwire re-renders the component template and returns the updated HTML in the AJAX response
5. cbwire is using the amazing [Livewire](https://laravel-livewire.com) JavaScript library to mutate the DOM based on our state changes.

## Pretty cool, right?

* We built a reactive counter.
* The counter updates without any page refresh.
* We didn't write any JavaScript.
* We didn't mess with webpack or JavaScript compilation.
* We never left CFML.:nerd:

We're just getting warmed up! cbwire is transforming the way we build CFML applications, and we think you're going to love it also.

## Credits

cbwire is built on [Livewire](https://laravel-livewire.com) and wouldn't exist if it wasn't for the efforts of Caleb Porzio ( creator of [Livewire](https://laravel-livewire.com), [Alpine.js](https://github.com/alpinejs/alpine) ) and the PHP community.

The cbwire module for ColdBox is written and maintained by [Grant Copley](https://twitter.com/grantcopley), [Luis Majano](https://twitter.com/lmajano), and [Ortus Solutions](https://www.ortussolutions.com).

## Project Support

Please consider becoming one of our lovingly esteemed [Patreon supporters](https://www.patreon.com/ortussolutions).


# Installation

Install [CommandBox](https://www.ortussolutions.com/products/commandbox).

Within the root of your project, run:

```bash
box install cbwire
```

If you want the latest bleeding-edge, run:

```bash
box install cbwire@be
```

## Requirements

* Adobe ColdFusion 2018+ or Lucee 5+
* ColdBox 6+


# Configuration

You can alter cbwire's behavior by overriding settings in your `config/ColdBox.cfc` file.

```javascript
// File: ./config/ColdBox.cfc

component{
    function configure() {
        moduleSettings = {
            cbwire = {
                "throwOnMissingSetterMethod" : false,
                "componentLocation": "wires"
            }
        };
     }
}

```

{% hint style="info" %}
Overriding the module settings is optional. All settings come with a default that is used if no overrides are provided. See [Overriding Module Settings](https://coldbox.ortusbooks.com/hmvc/modules/moduleconfig/module-settings#overriding-module-settings) in the ColdBox documentation for additional reference.
{% endhint %}

### throwOnMissingSetter

Set as `true` to throw a `WireSetterNotFound` exception if the incoming wire request tries to update a  property without a setter on our component. Otherwise, missing setters are ignored. **Defaults to false**.

## componentLocation

The relative folder path where the cbwire components are stored. **Defaults to `wires`**.


# Creating Components

You can scaffold cbwire components quickly using the [commandbox-cbwire](https://github.com/commandbox-modules/commandbox-cbwire) module.

## Installing commandbox-cbwire

To get started open the [CommandBox ](https://commandbox.ortusbooks.com/)binary or enter the shell by typing `box` in your terminal or console. Then let's install our scaffolding module.

```
install commandbox-cbwire
```

## Creating Components

Let's create a **Counter** cbwire component that we will use to list our favorite movies.

```javascript
cbwire create Counter
// Created /wires/Counter.cfc
// Created /views/wires/counter.cfm
// Created /tests/specs/integration/wires/CounterTest.cfc
```

You can provide named arguments as well.

```javascript
cbwire create name=Counter views=false
// Created /wires/Counter.cfc
// Created /tests/specs/integration/wires/CounterTest.cfc
```

Below is the entire signature of arguments you can provide to the `create` command.

```javascript
/**
    * @name Name of the component to create without the .cfc.
    * @actions Comma-delimited list of actions to generate.
    * @views Generate a view for the cbwire component.
    * @viewsDirectory Directory where your views are stored. Only used if views is set to true.
    * @integrationTests Generate the integration test component
    * @testsDirectory Your integration tests directory. Only used if integrationTests is true
    * @directory Base directory to create your handler in and creates the directory if it does not exist. Defaults to 'handlers'.
    * @description Component hint description.
    * @open Opens the component (and test(s) if applicable) once generated.
    **/
    function run(
    required string name,
    string actions = "",
    boolean views = true,
    string viewsDirectory = "views/wires",
    boolean integrationTests = true,
    string testsDirectory = "tests/specs/integration/wires",
    string directory = "wires",
    string description = "I am a new cbwire component.",
    boolean open = false
)
```


# Rendering Views

### renderIt()&#x20;

You can set your component's template by defining a `renderIt()` method on your component.

```javascript
component extends="cbwire.models.Component" {

    function renderIt(){
        // Renders ./views/wires/myView.cfm
        return this.renderView( "myView" );
    }

}
```

### variables.view

You can also set your component template using `variables.view` as an alternative to renderIt().

```javascript
component extends="cbwire.models.Component" {
    variables.view = "myView";
}

```

### Implicit Lookup

If you haven't set your component's view using `renderIt()` or `variables.view`, cbwire will look for a file that matches your component's file name.

```javascript
// File: ./wires/Counter.cfc
component extends="cbwire.models.Component" {
    // No explicit view defined.
}
```

For the `Counter.cfc` example above, cbwire will attempt to render a view located under **./views/wires/counter.cfm**

{% hint style="info" %}
File names should be lowercase when using Implicit Lookups. This is to avoid issues on case-sensitive file systems.
{% endhint %}

### View Example

```xml
// File: ./views/wires/counter.cfm
<!--- GOOD --->
<cfoutput>
    <div>
        <button wire:click="increment">Increment Counter</button>
    </div>
</cfoutput>

<!--- BAD --->
<cfoutput>
    <button wire:click="increment">Does Not Work</button>
</cfoutput>
```

{% hint style="warning" %}
Be sure that cbwire can bind onto your component's view by including an outer element such as`<div>`. If an outer element is not detected, cbwire will throw an `OuterElementNotFound`exception.
{% endhint %}


# Data Properties

Similar to Vue.js and other frontend JavaScript frameworks, you can define and initialize reactive properties on your cbwire components.

## Initializing Properties

You can define and initialize reactive properties on your cbwire components using `variables.data`.&#x20;

{% hint style="success" %}
When data properties are mutated, the UI will update also.
{% endhint %}

```javascript
// File: wires/Counter.cfc
component extends="cbwire.models.Component"{
    variables.data = {
        "counter": 0
    };
    ...
}
```

## Referencing Properties

You can reference a property directly in your component using `variables.data.[ property name ]`.

```javascript
// File: wires/Counter.cfc
component extends="cbwire.models.Component"{

    // Data properties
    variables.data = {
        "counter": 0
    };
    
    // Action called from UI
    function increment(){
        variables.data.counter += 1;
    }
    ...
}
```

You can also reference any defined properties from your cbwire component view using `args.[ property name  ]`.

```xml
// File: views/wires/counter.cfm
<cfoutput>
<div>
    <h1>Counter</h1>
    <div>Count: #args.counter#</div>
</div>
</cfoutput>
```

## Things To Know

Your component's private `variables` scope will hold your data property definitions and current values, which is seemingly secure, but it's necessary to be cautious about what you store. cbwire communicates with the server via Livewire using AJAX requests and includes the current state of the data properties within those requests.

{% hint style="success" %}
cbwire includes the current values of the data properties during requests to determine what state has changed and if Livewire should update the [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction).
{% endhint %}

{% hint style="danger" %}
You should NEVER store sensitive data ( such as passwords, SSNs ) that you wouldn't want your application's users to see.
{% endhint %}

{% hint style="info" %}
Data properties can only be data types that are castable to JavaScript data types, such as CFML strings, numeric, arrays, structs, or booleans.
{% endhint %}


# Actions

Actions in cbwire are methods in your cbwire component that are invoked when user interactions occur. Once an action has been invoked, the component's template is re-rendered.

```javascript
// File: ./wires/Counter.cfc
component extends="cbwire.model.Component"{

    // Data property
    variables.data = {
        "counter": 0
    };

    // Action
    function increment(){
        variables.data.counter += 1;
    }
}
```

```xml
<div>
    <button wire:click="increment">Increment Counter</button>
</div>
```


# Events

You can emit events from your cbwire components, views, and also direct from JavaScript. Listeners can be defined to execute specific actions.

You can fire events from within views, components, or by using the global `cbwire` JavaScript object.

### From View

```markup
<button wire:click="$emit( 'counterIncremented' )">
```

### From Component

```javascript
this.emit( "counterIncremented" );
```

### From Javascript Global

```xml
<script>
    cbwire.emit( 'counterIncremented' );
</script>
```

## Event Listeners

You can register event listeners on a component by defining `variables.listeners`.

```javascript
component extends="cbwire.models.Component"{

	variables.listeners = {
		"counterIncremented": "tweetAboutIt"
	};

	function tweetAboutIt(){
		// Blow up Twitter
	}

	...
}
```

{% hint style="success" %}
cbwire will invoke the `tweetAboutIt` method on the component if any other component on the same page emits a `counterIncremented` event.&#x20;
{% endhint %}

{% hint style="info" %}
When defining your listeners, it is good to put your listener's names in quotation marks, as we have in our component above. \
\
`"counterIncremented": "tweetAboutIt"`

JavaScript keys are case-sensitive. You can preserve the key casing in CFML by surrounding your listener names in quotations. Without the quotations, CFML will convert the key to all uppercase, such as `TWEETABOUTIT`. :upside\_down:&#x20;
{% endhint %}

## Event Listeners In JavaScript

```javascript
// File: ./views/wires/myView.cfm
<script>
    cbwire.on( 'counterIncremented', counter => {
        alert( 'The counter was incremented with a value of: ' + counter );
    })
</script>
```


# Lifecycle Events

## Component Wiring

![](https://2790241902-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MXiNYsHUJlavmFh1GPp%2Fuploads%2FLg5mpSdtLkDycdY7OAyV%2Fimage.png?alt=media\&token=424c1e7d-9c24-42bb-89eb-cacbb803b54b)

## mount( event, rc, prc, parameters )

Runs **once** when the component is initially wired.

```javascript
component extends="cbwire.models.Component" {

    function mount( event, rc, prc, parameters ){
        variables.data.incomingValue = event.getValue( "someField" );
    }

}
```

## <br>


# Redirecting

You can redirect users from your cbwire components similar to how you would in ColdBox using `relocate`.

```javascript
// File: ./wires/FindADeveloper.cfc

component extends="cbwire.models.Component"{

    function findADev(){
        return this.relocate( URL="https://www.ortussolutions.com" );
    }
    
    function renderIt(){
        return this.renderView( "wires/findADev" );
    }
}

// File: ./views/wires/findADev.cfm

<cfoutput>
<div>
    <button wire:click="findADev">Help mah code!</button>
</div>
</cfoutput>
```

In fact, cbwire uses ColdBox's internal `relocate()` method, so any of the arguments that ColdBox accepts can also be used with cbwire.

```javascript
/**
 * Relocate user browser requests to other events, URLs, or URIs.
 *
 * @event The name of the event to run, if not passed, then it will use the default event found in your configuration file
 * @URL The full URL you would like to relocate to instead of an event: ex: URL='http://www.google.com'
 * @URI The relative URI you would like to relocate to instead of an event: ex: URI='/mypath/awesome/here'
 * @queryString The query string or struct to append, if needed. If in SES mode it will be translated to convention name value pairs
 * @persist What request collection keys to persist in flash ram
 * @persistStruct A structure key-value pairs to persist in flash ram
 * @addToken Wether to add the tokens or not. Default is false
 * @ssl Whether to relocate in SSL or not
 * @baseURL Use this baseURL instead of the index.cfm that is used by default. You can use this for ssl or any full base url you would like to use. Ex: https://mysite.com/index.cfm
 * @postProcessExempt Do not fire the postProcess interceptors
 * @statusCode The status code to use in the relocation
 */
void function relocate(
    event,
    URL,
    URI,
    queryString,
    persist,
    struct persistStruct,
    boolean addToken,
    boolean ssl,
    baseURL,
    boolean postProcessExempt,
    numeric statusCode
);
```


# Logging

We inject a [LogBox](https://logbox.ortusbooks.com/) *logger* into all cbwire Components to provide you with built-in logging.

```javascript
component extends="cbwire.models.Component"{

    function mount(){
        log.info( "mount() called" );
    }

    function someAction(){
        log.debug( "someAction() called" );
    }

}
```

You can also access the LogBox parent object using `getLogBox()`.

```javascript
component extends="cbwire.models.Component"{

    function mount(){
        var logbox = getLogBox();
        var logger = logbox.getRootLogger();
        log.info( "Logging with the root logger!" );
    }

}
```


# Loading States

cbwire via Livewire uses AJAX requests to invoke component actions on our wire objects. There are cases when this may involve a long-running process, such as completing a cart checkout, and the page may not respond instantly to a user event like a click. cbwire allows you to effortlessly display loading states, such as showing and hiding elements, adding and removing classes, or toggling HTML attributes until the server responds.

Loading States can make your apps feel responsive and user-friendly.

## Toggling Elements

Let's take a look at a checkout action that takes too long.

```javascript
// File: ./wires/Cart.cfc
component extends="cbwire.models.Component"{

    function checkout(){
        sleep( 5000 ); // optimize this code yo!
    }

    function $renderIt(){
        return this.$renderView( "wires/cart" );
    }
}
```

We can annotate our `<div>` with `wire:loading` to display *Processing Payment* while the checkout action is running.

```xml
// File: ./views/wires/cart.cfm
<div>
    <button wire:click="checkout">Checkout</button>

    <div wire:loading>
        Processing Payment...
    </div>
</div>
```

After the checkout action completes, the *Processing Payment* output will disappear. :wave:&#x20;

## Toggling Attributes

```xml
<div>
    <button wire:click="checkout" wire:loading.attr="disabled">
        Checkout
    </button>
</div>
```

## Delay Loading State

Sometimes your component actions complete at the speed of light, and the user doesn't have enough time to see the elements you want to be displayed. You can add a `.delay` modifier to delay showing your HTML elements for *200ms*.

```xml
// File: ./views/wires/cart.cfm
<div wire:loading.delay>...</div>
```

## &#x20;Display Property

Loading State elements are set with a CSS property of `display: inline-block;` by default. You can override this behavior by using various annotation modifiers.

```xml
// File: ./views/wires/cart.cfm
<div wire:loading.flex>...</div>
<div wire:loading.grid>...</div>
<div wire:loading.inline>...</div>
<div wire:loading.table>...</div>
```

## Hide During Loading State

If you would like to display an element EXCEPT during a loading state, you can apply the `wire:loading.remove` annotation.

```xml
// File: ./views/wires/cart.cfm
<div>
    <button wire:click="checkout">Checkout</button>

    <div wire:loading.remove>
        Hide Me While Loading...
    </div>
</div>
```


# Polling

You can add a `wire:poll` annotation to your elements to poll for changes for a set interval. By default, this interval is set to every *2 seconds*.

```xml
<div wire:poll>
    Current time: #now()#
</div>
```

You can append a different interval time to your annotation as well.

```xml
<div wire:poll.5000ms>
    Current time: #now()#
</div>
```

{% hint style="info" %}
Polling for changes over AJAX is lightweight and is often a good alternative to strategies such as Pusher or WebSockets.&#x20;
{% endhint %}

### Invoking Method

If you would like to invoke a method during each poll interval, you can do so by specifying a method name.

```xml
<div wire:poll="checkIfCoffeeIsReady">
    Current time: #now()#
</div>
```


# Prefetching

You can prefetch an action's results on mouseOver using the `.prefetch` modifier.&#x20;

```xml
// File: ./views/wires/movie.cfm
<div>
    <button wire:click.prefetch="togglePreview">Show Preview</button>

    <cfif args.showPreview>
        <!-- Preview goes here -->
    </cfif>
</div>
```

```javascript
// File: ./wires/Movie.cfc
component extends="cbwire.models.Component"{

    variables.data = {
        "showPreview": false
    };

    function togglePreview(){
        variables.data.contentIsVisible = true;
    }
    
    function renderIt(){
        return this.renderView( "wires/movie" );
    }
}
```

{% hint style="success" %}
In the example here, cbwire will invoke ( prefetch ) the `togglePreview` action when the user mouses over the button. The results of the fetch are not displayed until the user clicks the 'Show Preview' button.
{% endhint %}

{% hint style="warning" %}
Prefetching works well for actions that do not perform any side effects, such as mutating session data or writing to a database. If the action you are "pre-fetching" does have side effects, you may encounter unpredictable results.
{% endhint %}


# Offline State

### CSS Classes

You can append `.class` to your `wire:offline` annotations and specify a CSS class to toggle when the user is offline.

```javascript
<div wire:offline.class="bg-gold-300"></div>
```

You can also specify classes you want to be removed when offline using `:wire:offline.class.remove`.

```javascript
<div wire:offline.class.remove="bg-gold-300" class="bg-gold-300"></div>
```


# Dirty States


# Defer Loading


# AlpineJS


# Inline Scripts


# Testing


# Security


# Troubleshooting


# CommandBox Commands


# Introduction

CBWIRE is a ColdBox module that makes building modern, reactive CFML apps a breeze without the need for JavaScript frameworks such as Vue or React, and without the hassle of creating unnecessary APIs.

<figure><img src="https://1380171784-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXiNYsHUJlavmFh1GPp%2F-MdyzqNxu6GJtqIN1E04%2F-Mdz-Lp0mrS43T5i6qGn%2Flogo.png?alt=media&amp;token=c30d87f7-f915-4cf1-9ee8-f8e9b27c5493" alt=""><figcaption></figcaption></figure>

Are you tired of the challenges that come with building modern CFML apps? [ColdBox](https://coldbox.ortusbooks.com/) makes server-side app development a breeze, but sometimes the client-side is a whole different story. With powerful JavaScript frameworks like Vue and React, it can be a difficult and time-consuming process to create your web apps.&#x20;

But what if you could have the best of both worlds: the power of Vue and React with the simplicity of CFML? Impossible, you say? Think again!&#x20;

Introducing **CBWIRE: Power up your CFML and make your app dreams a reality!**

## Let's create a counter...

Install [CommandBox](https://www.ortussolutions.com/products/commandbox), then from our terminal, run:

```bash
mkdir cbwire-demo
cd cbwire-demo
box coldbox create app
box install cbwire@be
box server start
```

Next, add `wireStyles()` and `wireScripts()` to our layout. This is required for CBWIRE to do it's magic.&#x20;

Let's also insert a counter element into the page using `wire( "Counter" )`.

```markup
<!--- ./layouts/Main.cfm --->
<cfoutput>
<!doctype html>
<html>
<head>
    #wireStyles()#
</head>
<body>
    #wire( "Counter" )#
    #wireScripts()#
</body>
</html>
</cfoutput>

```

Let's define our counter [Wire](/v2-1/essentials/creating-components).&#x20;

```javascript
// ./wires/Counter.cfc
component extends="cbwire.models.Component" {

    // Data Properties
    data = {
        "counter": 0
    };

    // Actions
    function increment(){
        data.counter += 1;
    }
}

```

Finally, let's create a [Template](/v2-1/essentials/templates) for our counter Wire. Notice that we've added a `wire:click` [directive](/v2-1/template-features/directives) to our button.

```markup
<!--- ./views/wires/counter.cfm --->
<cfoutput>
<div>
    <div>Count: #args.counter#</div>
    <button wire:click="increment">
        +
    </button>
</div>
</cfoutput>
```

Refresh the page. You now have a reactive counter that increments when you click the plus button without any page refreshing!

![](https://1380171784-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FLu4qHbQzxzDxUIBU3WJs%2Fuploads%2FQjZTgensFIHOTGZPJUG6%2F2022-02-08%2016.02.25.gif?alt=media\&token=19a20084-77e5-4e12-b1da-c8f0722890c0)

## What!? How?

1. CBWIRE renders our *Counter* Wire template. Our counter value defaults to 0.
2. When a user clicks the plus button, CBWIRE detects the event and makes an XHR request to the server.
3. CBWIRE picks up the XHR request and invokes the *increment* action.
4. The *increment* method updates the counter state by 1.
5. CBWIRE re-renders the template and returns the updated HTML in the XHR response
6. CBWIRE detects any state changes and uses Livewire to mutate the DOM.

## Awesome, right?

* We built a reactive counter with no page refreshing.
* We didn't write any JavaScript.
* We didn't use webpack or mess with JavaScript compilation.&#x20;
* We never left CFML.:nerd:&#x20;

CBWIRE is transforming the way we build CFML applications, and we think you're going to love it also!

## Credits

CBWIRE is built on [Livewire](https://laravel-livewire.com/) and wouldn't exist without [Caleb Porzio](https://twitter.com/calebporzio) ( creator of [Livewire](https://laravel-livewire.com/), [Alpine.js](https://github.com/alpinejs/alpine) ) and the PHP community.&#x20;

The CBWIRE module for ColdBox is written and maintained by [Grant Copley](https://twitter.com/grantcopley), [Luis Majano](https://twitter.com/lmajano), and [Ortus Solutions](https://www.ortussolutions.com/).

## Project Support

Please consider becoming one of our lovingly esteemed [Patreon supporters](https://www.patreon.com/ortussolutions).

## Resources

* CBWIRE Examples: <https://github.com/grantcopley/cbwire-examples>
* ForgeBox: <https://forgebox.io/view/cbwire>
* GitHub Repository: <https://github.com/coldbox-modules/cbwire>
* API Docs: <https://apidocs.ortussolutions.com/#/coldbox-modules/cbwire/>
* Issue Tracker: <https://github.com/coldbox-modules/cbwire/issues>
* Task List Demo: <https://github.com/grantcopley/cbwire-task-list-demo>
* Form Validation Demo: <https://github.com/grantcopley/cbwire-signup-form-demo>
* Up and Running Screencast: <https://cfcasts.com/series/ortus-single-video-series/videos/up-and-running-with-cbwire>
* Into The Box 2021 Presentation: <https://cfcasts.com/series/into-the-box-2021/videos/cbwire-coldbox-+-livewire-grant-copley>
* Ortus Webinar 2022: <https://cfcasts.com/series/ortus-webinars-2022/videos/grant-copley-on-cbwire-+-alpine_js>


# Release History

In this section, you will find the release notes for each version we release under this major version. If you are looking for the release notes of previous major versions use the version switcher at the top left of this documentation book.&#x20;


# What's New With 2.2

## 01/09/2022

### Added

[CBWIRE-99](https://ortussolutions.atlassian.net/browse/CBWIRE-99): Implement lifecycle hook onHydrate().

[CBWIRE-100](https://ortussolutions.atlassian.net/browse/CBWIRE-100): Implement lifecycle hook onHydrate\[Property]\().

[CBWIRE-103](https://ortussolutions.atlassian.net/browse/CBWIRE-103): Implement an automatic trim() for all data properties.

[CBWIRE-124](https://ortussolutions.atlassian.net/browse/CBWIRE-124): Implement the ability to interact with CBWIRE component from JavaScript using cbwire.find( '#args.\_id#' ).

[CBWIRE-125](https://ortussolutions.atlassian.net/browse/CBWIRE-125): Add configuration setting 'enableTurbo' to automatically include everything needed to work with Turbo for single page applications.

[CBWIRE-130](https://ortussolutions.atlassian.net/browse/CBWIRE-130): Add ability to call reset() without passing a key to reset all data properties to their original values.

### Changed

[CBWIRE-93](https://ortussolutions.atlassian.net/browse/CBWIRE-93): Implement onMount() method instead of mount().

### Fixed

[CBWIRE-121](https://ortussolutions.atlassian.net/browse/CBWIRE-121): DocBox generated docs are failing because of file structure.

[CBWIRE-126](https://ortussolutions.atlassian.net/browse/CBWIRE-126): Listeners are being fired immediately when calling emit() when the listener is defined on the same component, which they shouldn't.

[CBWIRE-127](https://ortussolutions.atlassian.net/browse/CBWIRE-127): onHydrate() is firing after actions are performed.

[CBWIRE-129](https://ortussolutions.atlassian.net/browse/CBWIRE-129): Computed properties are not being rendered before actions are called.


# What's New With 2.1

## 11/26/2022

### Added

[CBWIRE-111](https://ortussolutions.atlassian.net/browse/CBWIRE-111) Ability to output component template direct from onRender() method instead of defining a .cfm template in wire/views.

### Fixed

[CBWIRE-119](https://ortussolutions.atlassian.net/browse/CBWIRE-119) Computed properties that do not return a value result in the error 'variable \[VALUE] doesn't exist

[CBWIRE-118](https://ortussolutions.atlassian.net/browse/CBWIRE-118) Nested components are causing the template rendering only to render the last nested template

[CBWIRE-117](https://ortussolutions.atlassian.net/browse/CBWIRE-117) Struct values are not being passed to the template and are instead being replaced with an empty string

[CBWIRE-116](https://ortussolutions.atlassian.net/browse/CBWIRE-116) CBWIRE doesn't work when the ColdBox app is in a subdirectory

[CBWIRE-115](https://ortussolutions.atlassian.net/browse/CBWIRE-115) Getting errors when rendering component templates in the latest version of ColdBox

[CBWIRE-96](https://ortussolutions.atlassian.net/browse/CBWIRE-96) Nested components are not rendering


# What's New With 2.0

## 08/30/2022

### Added

CBWIRE-24: File Uploads

CBWIRE-55: Ability to write unit tests for components

CBWIRE-59: Ability to override the default 'wires' folder location

CBWIRE-60: noRender() method to prevent template rendering during actions

CBWIRE-61: Implement dirty property tracking

CBWIRE-65: Invoke computed properties during template rendering and only execute once per request

CBWIRE-70: Ability to specify a 'moduleRootURI' setting to change the URI path for cbwire

CBWIRE-71: Upgrade Livewire JS to v2.10.6

CBWIRE-81: Option to specify the component's template path using this.template instead of defining renderIt() method.

CBWIRE-82: Disable browser caching on XHR responses

CBWIRE-83: Reduce payload bloat by removing unnecessary data in XHR requests and responses

CBWIRE-84: Move internal methods to a separate Engine object to avoid collisions with user-defined methods

CBWIRE-85: Reject incoming XHR request if 'X-Livewire' HTTP Header is not present

CBWIRE-86: Specify null values for data properties

CBWIRE-87: Dependency injection capabilities to cbwire components

CBWIRE-90: Update to match Livewire's current incoming and outgoing HTTP responses

CBWIRE-91: Ability to use Turbo to create Single-page Applications ( SPAs )

### Fixed

CBWIRE-73: Calling reset( "someProperty" ) throws error

CBWIRE-74: Browser back history doesn't work

CBWIRE-80: On subsequent renderings of components, it's changing the unique id and causing DOM diff issues

CBWIRE-88: Livewire expects params to be an array

CBWIRE-89: Not passing parameters when calling update methods


# Getting Started

With CommandBox, you can start building reactive CFML apps in seconds.

## Requirements

* Adobe ColdFusion 2018+ or Lucee 5+
* ColdBox 6+

## Installation

Install [CommandBox](https://www.ortussolutions.com/products/commandbox).

Within the root of your project, run:

```bash
box install cbwire
```

If you want the latest bleeding edge, run:

```bash
box install cbwire@be
```

## Layout Setup

You need to add references for `wireStyles()` and `wireScripts()` to your layout file.

```html
<!--- ./layouts/Main.cfm --->
<cfoutput>
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>CBWIRE Example</title>
        #wireStyles()#
    </head>
    <body>
        
        <!--- JavasScript references below --->
        #wireScripts()#
    </body>
</html>
</cfoutput>
```

{% hint style="warning" %}
CBWIRE will not work if you do not add these to your layout.
{% endhint %}

## Inserting Wires

You can insert [Wires](/v2-1/essentials/creating-components) anywhere in your layout or ColdBox views using `wire( componentName )`.

```html
<!--- ./layouts/Main.cfm --->
<body>
    <!--- Insert our task list wire here --->
    #wire( "TaskList" )#
            
    <!--- JavasScript references below --->
    #wireScripts()#
</body>
```

```html
<!--- ./views/someview.cfm --->
<cfoutput>
    <div>#wire( "TaskList" )#</div>
</cfoutput>
```


# Examples

See CBWIRE in action!

## Git Repository

In addition to the examples above, we have a GitHub repo that contains more examples of CBWIRE. Each example includes both the code to generate the example and a section where you can see the results in real-time.

<https://github.com/grantcopley/cbwire-examples>

<figure><img src="https://1380171784-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FLu4qHbQzxzDxUIBU3WJs%2Fuploads%2FqKXOiQJpvC1lftKF9WsI%2Fimage.png?alt=media&amp;token=46e5f4eb-212b-4e97-ae82-d4e1f1882f5a" alt=""><figcaption><p>Homepage listing various CBWIRE examples</p></figcaption></figure>

<figure><img src="https://1380171784-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FLu4qHbQzxzDxUIBU3WJs%2Fuploads%2F61Pfb1hpTOnt7yOKeSmP%2Fimage.png?alt=media&amp;token=73a3ef76-0322-44b2-b9e1-598e3959c377" alt=""><figcaption><p>Individual page showing form validation in CBWIRE</p></figcaption></figure>


# Configuration

Alter CBWIRE's behavior with these nifty configuration options.

## ColdBox.cfc

You can alter any default behavior by overriding settings in your `config/ColdBox.cfc` file.

```javascript
// File: ./config/ColdBox.cfc
component{
    function configure() {
        moduleSettings = {
            cbwire = {
                "enableTurbo": false,
                "maxUploadSeconds": 5 * 60, // 5 minutes
                "throwOnMissingSetterMethod" : false,
                "trimStringValues": false,
                "wiresLocation": "myWires",
                "useComputedPropertiesProxy": false
            }
        };
     }
}

```

{% hint style="info" %}
Overriding the module settings is optional. All settings come with a default that is used if no overrides are provided. See [Overriding Module Settings](https://coldbox.ortusbooks.com/hmvc/modules/moduleconfig/module-settings#overriding-module-settings) in the ColdBox documentation for additional reference.
{% endhint %}

### enableTurbo

Set as true to enable [Turbo](/v2-1/integrations/turbo), which causes any clicked links or form submissions to be performed in the background via AJAX and updates the DOM without reloading the page. Great when developing single-page, VueJS-like applications. **Defaults to false.**

### maxUploadSeconds

The maximum amount of time allowed for uploads to complete.

### throwOnMissingSetter

Set as true to throw a WireSetterNotFound exception if the incoming wire request tries to update a property without a setter on our [Wire](/v2-1/essentials/creating-components). Otherwise, missing setters are ignored. **Defaults to false**.

### trimStringValues

When set to true, any data properties that contain strings will be automatically trimmed. Great for form inputs. **Defaults to false**.

### wiresLocation

The relative folder path where [Wires](/v2-1/essentials/creating-components) are stored. **Defaults to 'wires'**.

### useComputedPropertiesProxy

When set to true, Computed Properties will be proxied. See [Computed Properties (Proxied)](/v2-1/essentials/computed-properties/computed-properties-proxied).


# Wires

Wires are reactive UI elements you create. They include a powerful feature-set provided by CBWIRE.

Wires primarily consist of the following:

* [Data Properties](/v2-1/essentials/properties)\
  Reactive properties that we can easily change.
* [Computed Properties](/v2-1/essentials/computed-properties)\
  Properties that are computed every time our template is rendered.
* [Actions](/v2-1/essentials/actions)\
  Methods that make state changes to our data properties.
* [Events and Listeners](/v2-1/essentials/events)\
  Listen for emitted events within Wires or client-side JavaScript.
* [Templates](/v2-1/essentials/templates)\
  HTML to render our Wire.

## Basic Example

```javascript
// File: wires/TaskList.cfc
component extends="cbwire.models.Component" {

    // Data properties
    data = {
        "task": "",
        "tasks": []
    };
    
    // Computed properties
    computed = {
        "counter": function() {
            return arrayLen( data.tasks );
        }
    };
    
    // Listeners
    listeners = {
        "taskAdded": "sendEmail"
    };
    
    // Action
    function addTask(){
        data.tasks.append( data.task );
        this.emit( "taskAdded", data.task );
    }
    
}
```

```html
<!--- /views/wires/tasklist.cfm --->
<cfoutput>
<div>
    <div>Number of tasks: #args.computed.counter()#</div>
    <div><input wire:model="task"></div>
    <div><button wire:click="addTask">Add Task</button></div>
</div>
</cfoutput>
```

## Scaffolding

You can scaffold Wires quickly using the [commandbox-cbwire](https://github.com/commandbox-modules/commandbox-cbwire) module.

From our CommandBox shell, type:

```
install commandbox-cbwire
```

Let's create a **Counter** Wire that we will use to list our favorite movies.

```javascript
cbwire create Counter
// Created /wires/Counter.cfc
// Created /views/wires/counter.cfm
// Created /tests/specs/integration/wires/CounterTest.cfc
```

You can provide named arguments as well.

```javascript
cbwire create name=Counter views=false
// Created /wires/Counter.cfc
// Created /tests/specs/integration/wires/CounterTest.cfc
```


# Data Properties

Define reactive properties for your UI Wires with just a few lines of code.

Similar to Vue.js and other frontend JavaScript frameworks, you can define reactive properties on your [Wires](/v2-1/essentials/creating-components).

## Defining Properties

You can define and initialize properties on your [Wires](/v2-1/essentials/creating-components) using `data`.&#x20;

```javascript
component extends="cbwire.models.Component"{
    data = {
        "task": ""
    };
}
```

{% hint style="warning" %}
Data Properties are parsed and tracked by Livewire and JavaScript, therefore only data types that are castable to JavaScript can be stored in Data Properties (strings, numeric, arrays, structs, or booleans).\
\
If you are needing more complex data types for your templates, use [Computed Properties](/v2-1/essentials/computed-properties) instead.
{% endhint %}

{% hint style="success" %}
When data properties are mutated, the UI will update also.
{% endhint %}

## Accessing Properties

### Data Variable

You can reference a property using `data.[propertyName]`.

```javascript
component extends="cbwire.models.Component"{

    property name="taskService" inject="TaskService@myapp";
    
    // Data properties
    data = {
        "task": ""
    };
    
    // Action
    function addTask(){
        taskService.create( data.task );
    }
}
```

### Getters

Getter methods are automatically available for your properties based on the property's name. You to access the property within your Wire using `this.get[propertyName]()`.&#x20;

```javascript
component extends="cbwire.models.Component"{
    
    property name="taskService" inject="TaskService@myapp";

    // Data properties
    data = {
        "task": ""
    };
    
    // Action
    function addTask(){
        taskService.create( this.getTask() );
    }
}
```

{% hint style="success" %}
You can use this as an alternative to using `data`.
{% endhint %}

### Templates

You can reference data properties within your Wire's template using `args.[propertyName]`.

```xml
<cfoutput>
<div>
    <h1>Task</h1>
    <div>#args.task#</div>
</div>
</cfoutput>
```

## Resetting Properties

You can reset properties back to their original value using `reset()`.

```javascript
component extends="cbwire.models.Component"{

    // Data properties
    data = {
        "task": "Some task here"
    };

    // Action
    function resetForm() {
        data.task = "Another value";
        reset( "task" ); // Reverts data.task to 'Some task here'
    }

}
```

There are several ways to use reset.

```javascript
function someAction() {
    reset( "task" ); // resets 'task' data property
    reset( [ "task", "anotherprop" ] ); // reset multiple properties at once
    reset(); // resets all properties
}
```

## Security

Your component's private `variables` scope will hold your data property definitions and current values, but it's necessary to be cautious about what you store.&#x20;

{% hint style="success" %}
The values of your data properties are included with each XHR response and Livewire uses these values to determine what should be updated in the [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction).
{% endhint %}

{% hint style="danger" %}
You should NEVER store sensitive data ( such as passwords, and SSNs ) that you wouldn't want your application's users to see.
{% endhint %}


# Computed Properties

Create dynamic properties for your UI Wires.

{% hint style="warning" %}
If you are on CBWIRE version 2.3.x  and have enabled the configuration property **useComputedPropertiesProxy**, then you will need to follow [this guide here](/v2-1/essentials/computed-properties/computed-properties-proxied) instead as this fundamentally changes how computed properties are referenced and accessed.&#x20;
{% endhint %}

Computed Properties are dynamic properties and are helpful for deriving values from a database or another persistent store like a cache.&#x20;

Computed Properties are similar to [Data Properties](/v2-1/essentials/properties) with some key differences:

* They are declared as inline functions using `computed`.
* They can return any type of CFML value or object, not just values that can be serialized and parsed by JavaScript like Data Properties.

{% hint style="success" %}
See the [Wire Lifecycle](/v2-1/essentials/lifecycle-events#order-of-operations) page for details on when Computed Properties are executed.
{% endhint %}

{% hint style="info" %}
Computed Properties are cached for the lifetime of the request. Meaning, if you reference your Computed Property three times in your [Template](#templates) or from within a wire [Action](/v2-1/essentials/actions), it will only execute once.
{% endhint %}

## Defining Properties

You can define Computed Properties on your [Wires](/v2-1/essentials/creating-components) using `computed`. Each Computed Property is invoked only once during a single request cycle.

```javascript
component extends="cbwire.models.Component" {

    property name="taskService" inject="taskService@myapp";

    // Computed Properties
    computed = {
        "allTasks": function() {
            return taskService.getAll();
        }
    };
}

```

## Accessing Properties

You can access your Computed Properties from within your [Actions](/v2-1/essentials/actions) using `computed.[propertyName]`.

```javascript
component extends="cbwire.models.Component" {

    property name="taskService" inject="taskService@myapp";

    // Computed Properties
    computed = {
        "allTasks": function() {
            return taskService.getAll();
        }
    };

    // Action
    function deleteTasks() {
        
        // Notice below we don't invoke the method using computed.allTasks().
        // We instead just use 'computed.allTasks'.
        // At this point, cbwire has rendered our computed properties
        // and overwritten the references with their result.
        if ( arrayLen( computed.allTasks ) {
            taskService.deleteAll();
        }

    }
}
```

### Getters

Getters are automatically created based on the property's name.&#x20;

In the example below, you to access the property using `this.getAllTasks()`. You can use this as an alternative to using `computed`.

```javascript
component extends="cbwire.models.Component" {

    property name="taskService" inject="taskService@myapp";

    // Computed Properties
    computed = {
        "allTasks": function() {
            return taskService.getAll();
        }
    };

    // Action
    function deleteTasks() {
        if ( arrayLen( this.getAllTasks() ) {
            taskService.deleteAll();
        }
    }
}
```

### Templates

You can access Computed Properties in your [Template](#templates) via the `args` scope.

```html
<cfoutput>
<div>
    <ul>
        <cfloop array="#args.allTasks#" index="task">
            <li>#task#</li>    
        </cfloop>
    </ul>
</div>
</cfoutput>
```


# Computed Properties ( Proxied )

Create dynamic properties for your UI Wires.

{% hint style="warning" %}
You must be on CBWIRE version 2.3.5 or later and enable the [Configuration](/v2-1/essentials/configuration) setting **useComputedPropertiesProxy** to follow this guide.

Otherwise, please follow [this guide](/v2-1/essentials/computed-properties) instead.
{% endhint %}

{% hint style="success" %}
In CBWIRE 2.3.5, we introduced the ability to proxy Computed Properties, which offers several advantages, including:

* Computed Properties are passed around as closures and are only rendered when called.
* The ability to invoke Computed Properties anywhere they are needed (both Actions and Templates).
* The ability to cache Computed Property results to enhance performance.
  {% endhint %}

Computed Properties are dynamic properties and help derive values from a database or another persistent store like a cache.&#x20;

Computed Properties are similar to [Data Properties](/v2-1/essentials/properties) with some key differences:

* They are declared as inline functions using `computed`.
* They can return any CFML value or object.

## Defining Properties

Define Computed Properties in your [Wires](/v2-1/essentials/creating-components) using `computed`.&#x20;

```javascript
component extends="cbwire.models.Component" {

    property name="taskService" inject="taskService@myapp";

    // Computed Properties
    computed = {
        "allTasks": function() {
            return taskService.getAll();
        }
    };
}

```

## Accessing From Actions

You can access your Computed Properties from within your [Actions](/v2-1/essentials/actions) using `computed.[propertyName]()`.

```javascript
component extends="cbwire.models.Component" {

    // Computed Properties
    computed = {
        "allTasks": function() {
            // return something here
        }
    };

    // Action
    function deleteTasks() {      

        if ( arrayLen( computed.allTasks() ) {
            taskService.deleteAll();
        }

    }
}
```

## Accessing From Templates

You can access Computed Properties in your [Template](#templates) using `args.computed.[computedProperty]()`.

```html
<cfoutput>
<div>
    <ul>
        <cfloop array="#args.computed.allTasks()#" index="task">
            <li>#task#</li>    
        </cfloop>
    </ul>
</div>
</cfoutput>
```


# Actions

The magic sauce. Actions allow you to easily listen to page interactions and call a method on your Wires.

Actions provide an effortless way to track page interactions and invoke methods on your [Wires](/v2-1/essentials/creating-components), resulting in a re-render of the Wire's [Template](/v2-1/essentials/templates).

Here is a basic example of how to use it:

```javascript
component extends="cbwire.model.Component"{
  
    // Actions
    function addTask(){
      queryExecute( ... );
    }
}
```

```html
<!--- Template --->
<div>
    <button wire:click="addTask">Add Task</button>
</div>
```

## Invoking Actions

You can listen for browser events and invoke actions using a selection of various [Directives](/v2-1/template-features/directives). The directives follow the format: **wire:\[browser event]=\[action]**.

Some examples of events you can listen for include:

| Event   | Directive    |
| ------- | ------------ |
| click   | wire:click   |
| keydown | wire:keydown |
| submit  | wire:submit  |

Here are a few examples of each in HTML:

```html
<a href="" wire:click.prevent="doSomething">Do Something</a>

<button wire:click="doSomething">Do Something</button>

<input wire:keydown.enter="doSomething">

<form wire:submit.prevent="save">
    <button>Save</button>
</form>
```

You can listen for any browser events on elements by using the **wire:\[event]** directive, where \[event] is the event's name. For example, to listen for a "foo" event on a button element, you would use the following code:&#x20;

```html
<button wire:foo="someAction">
```

## Passing Parameters

You can pass parameters to your actions, such as here using `addTask('Some Task')`.

```html
<button wire:click="addTask('Some Task')">Add Task</button>
```

The parameter is then passed through to your [Actions](/v2-1/essentials/actions) via function arguments.

```javascript
// Action
function addTask( taskName ){

}
```

## Return Values

{% hint style="warning" %}
Actions shouldn't return any value. Return values are ignored.
{% endhint %}

## Accessing Data Properties

You can access data properties inside your actions directly using `data`.

```javascript
    data = {
        "task": ""
    };

    // Actions
    function clearTasks(){
        data.task = "";
    }
```

## Accessing Computed Properties

You can access Computed Properties inside your actions directly using `computed`.

```javascript
    // Computed Properties
    computed = {
        "tasks": function() {
            return queryExecute( "
                select *
                from tasks
            " );

        }
    };

    // Actions
    function deleteTasks(){
        if ( computed.tasks.recordCount ) {
            // query to delete the tasks...    
        } 
    }
```

{% hint style="info" %}
Notice that our Computed Property above is defined as a closure function, but once our deleteTasks() action is called, the computed property has already been rendered.
{% endhint %}

## Magic Actions

In CBWIRE, there are some "magic" actions that are usually prefixed with a "$" symbol:

| Function                      | Description                                            |
| ----------------------------- | ------------------------------------------------------ |
| $refresh                      | Will re-render the component without firing any action |
| $set( 'dataproperty', value ) | Shortcut to update the value of a property             |
| $toggle( 'dataproperty' )     | Shortcut to toggle boolean properties off and on       |

Consider the example below.

```html
<div>
    #args.message#
    <button wire:click="setMessageToHello">Say Hi</button>
</div>
```

You can instead call $set and avoid the need to create an Action named setMessageToHello.

```html
<div>
    #args.message#
    <button wire:click="$set( 'message', 'Hello' )">Say Hi</button>
</div>
```

It can also be used in the backend when listening for an event. For example, if you have one component that emits an event like this:

```javascript
function someAction() {
    emit( "some-event" );
}
```

Then in another component you can use a magic action for example $refresh() instead of having to point the listener to a method:

```javascript
component {
    listeners = {
        "some-event": "$refresh"
    };
}
```


# Templates

Your Wire's HTML. Simple as that. Honestly.

{% hint style="warning" %}
[Wires](/v2-1/essentials/creating-components) require a template that contains the HTML to be rendered.&#x20;
{% endhint %}

{% hint style="info" %}
By default, Templates exist within your project under `./views/wires/[templateName].cfm`. You can override the default template location with the configuration setting `templatesLocation.` *See* [*Configuration*](/v2-1/essentials/configuration)
{% endhint %}

## Implicit Path

If you haven't specified your template file name inside your Wire using **template**, a template will be implicitly loaded based on the Wire's file name.

```javascript
component extends="cbwire.models.Component" {
    // No template defined.
}
```

For the example above, the template `./views/wires/tasklist.cfm` will be rendered.

{% hint style="info" %}
File names should be lowercase when using Implicit Lookups. This is to avoid issues on case-sensitive file systems.
{% endhint %}

## Explicit Path

You can specify the path to your Template using `template`.&#x20;

```javascript
component extends="cbwire.models.Component" {
    template = "wires/tasklist"; // This will look for ./views/wires/tasklist.cfm

    // template = "path/to/tasklist"; <--- Can use folders
    
    // template = "tasklist.cfm"; <--- Can use .cfm if you like
}
```

{% hint style="warning" %}
In CBWIRE 1.x, you would define the template path using `view` but this has been deprecated and `template` should be used going forward.
{% endhint %}

## onRender

Instead of creating a .cfm template, you can define an onRender() method on your [Wire](/v2-1/essentials/creating-components).&#x20;

See the [Wire Lifecycle](/v2-1/essentials/lifecycle-events#onrender) page for additional details.

## Prevent Rendering

Within your [Actions](/v2-1/essentials/actions), you can call the method `noRender()` to prevent your template from re-rendering. This can reduce the returned payload size for actions that do not change the UI.&#x20;

```javascript
component extends="cbwire.model.Component"{
    // Action
    function updateSession(){
        // prevent UI updating
        noRender();
    }
}
```

## Outer Element

Be sure your template includes a single outer element such as`<div>`.&#x20;

```xml
<!--- GOOD --->
<cfoutput>
    <div>
        <button wire:click="addTask">Add Task</button>
    </div>
</cfoutput>

<!--- BAD --->
<cfoutput>
    <div>
        <button wire:click="addTask">Add Task</button>
    </div>
    <div>
        <h1>Tasks</h1>
    </div>
</cfoutput>
```

{% hint style="warning" %}
If an outer element is not detected, an **OuterElementNotFoundexception** is thrown.
{% endhint %}

{% hint style="success" %}
You can use something other than \<div>\</div>.
{% endhint %}


# Events & Listeners

You can emit events from both your Wires and JavaScript. Superb!

## Emitting Events

You can emit events from [Actions](/v2-1/essentials/actions), [Templates](/v2-1/essentials/templates), and JavaScript.

### Actions

Using the `emit` method:

```javascript
function someAction() {
    emit( "taskAdded" );
}
```

You can provide arguments to all listeners by passing an array as the second argument.

```javascript
function someAction() {
    emit( "taskAdded", [
        "some task",
        now()
    ] );
}
```

{% hint style="info" %}
When emitting events, arguments must be passed as an array to ensure proper positioning both within CFML and JavaScript.
{% endhint %}

### Templates

Using the `$emit()` method:

```markup
<button wire:click="$emit( 'taskAdded' )">
```

### JavaScript

Using the global `cbwire.emit()`:

```xml
<script>
    cbwire.emit( 'taskAdded' );
</script>
```

## Listeners

You can register event listeners on a Wire by defining `listeners`.

```javascript
component extends="cbwire.models.Component"{
    
    listeners = {
        "taskAdded": "clearCache"
    };

    function clearCache(){}
}
```

{% hint style="info" %}
The `clearCache` method will be invoked when a `taskAdded` event is emitted.
{% endhint %}

{% hint style="warning" %}
JavaScript keys are case-sensitive. You can preserve the key casing in CFML by surrounding your listener names in quotations.
{% endhint %}

### JavaScript

Listening to events that you emit in your [Actions](#actions) can be done using `cbwire.on()`.

```html
<script>
    cbwire.on( 'taskAdded', task => {
        console.log( 'A task was added. ');
    })
</script>
```


# Wire Lifecycle

Everything that has a beginning has an end. - The Oracle, Matrix

## Order of Operations

When a [Wire](/v2-1/essentials/creating-components) is initially loaded (before any background AJAX requests are performed), the Lifecycle Methods are executed in the following order.

1. onMount()
2. Render [Computed Properties](/v2-1/essentials/computed-properties)
3. onRender() or implicit [Template](/v2-1/essentials/templates) rendering

For background AJAX requests, lifecycle methods are executed in this order.

1. onHydrate\[DataProperty]\()
2. onHydrate()
3. Render [Computed Properties](/v2-1/essentials/computed-properties)
4. Execute [Actions](/v2-1/essentials/actions)
5. onRender() or implicit [Template](/v2-1/essentials/templates) rendering

## onMount

Runs only **once** when the Wire is initially wired.&#x20;

{% hint style="warning" %}
This does not fire during subsequent renderings for the Wire.
{% endhint %}

```javascript
component extends="cbwire.models.Component" {

    data = {
        "taskId": 0
    };

    function onMount( event, rc, prc, parameters ){
        data.taskId = event.getValue( "taskId" );
    }

}

```

{% hint style="warning" %}
onMount() replaces what was formerly mount(). The mount() method is deprecated and will be removed in future major releases of CBWIRE.
{% endhint %}

## onHydrate

Runs on subsequent requests, after the Wire is hydrated, but before [Computed Properties](/v2-1/essentials/computed-properties) are rendered, before an [Action](/v2-1/essentials/actions) is performed, or before onRender() is called.

```javascript
component extends="cbwire.models.Component" {

    data = {
        "hydrated": false
    };

    function clicked() {}

    function onHydrate( data ) {
        // Note that computed properties are not rendered yet
        data.hydrated = true;
    }

    function onRender( args ) {
        return "
            <div>
                <div>Hydrated: #args.hydrated#</div>
                <button wire:click='clicked'>Click me</button>
            </div>
        ";
    }
}
```

## onHydrate\[ DataProperty ]

Runs on subsequent requests, after a specific [Data Property](/v2-1/essentials/properties) is hydrated, but before [Computed Properties](/v2-1/essentials/computed-properties) are rendered, before an [Action](/v2-1/essentials/actions) is performed, or before onRender() is called.

```javascript
component extends="cbwire.models.Component" {

    data = {
        "count": 1
    };

    function onHydrateCount( data ) {
        // Note that computed properties are not rendered yet
        data.count += 1;
    }  
}
```

## onRender

Runs during the rendering of a [Wire](/v2-1/essentials/creating-components). If onRender() is defined on the Wire, CBWIRE will use what is returned as the component's template, otherwise it will perform a lookup for a view template. The `args` parameter is provided which contains both the [Data Properties](/v2-1/essentials/properties) and any rendered [Computed Properties](/v2-1/essentials/computed-properties).

```javascript
component extends="cbwire.models.Component" {

    data = {
        "rendered": true
    };
    
    computed = {
        "currentDate": function() {
            return now();
        }
    }

    function onRender( args ) {
        return "
            <div>
                <div>Rendered: #args.rendered# at #args.currentDate#</div>
            </div>
        ";
    }
}
```


# JavaScript

Seamlessly connect between the front-end and your server back-end using JavaScript and CFML.

## Lifecycle Hooks

CBWIRE gives you the opportunity to execute JavaScript during various events.

<table><thead><tr><th width="251">Hook</th><th>Description</th></tr></thead><tbody><tr><td>component.initialized</td><td>Called when a <a href="/v2-1/essentials/creating-components">Wire</a> has been initialized on the page by Livewire</td></tr><tr><td>element.initialized</td><td>Called when Livewire initializes an individual element</td></tr><tr><td>element.updating</td><td>Called before Livewire updates an element during its DOM-diffing cycle after a network roundtrip</td></tr><tr><td>element.updated</td><td>Called after Livewire updates an element during its DOM-diffing cycle after a network roundtrip</td></tr><tr><td>element.removed</td><td>Called after Livewire removes an element during its DOM-diffing cycle</td></tr><tr><td>message.sent</td><td>Called when a Livewire update triggers a message sent to the server via AJAX</td></tr><tr><td>message.failed</td><td>Called if the message send fails for some reason</td></tr><tr><td>message.received</td><td>Called when a message has finished its roudtrip, but before Livewire updates the DOM</td></tr><tr><td>message.processed</td><td>Called after Livewire processes all side effects (including DOM-diffing) from a message</td></tr></tbody></table>

```html
<script>
    document.addEventListener("DOMContentLoaded", () => {
        cbwire.hook('component.initialized', (wire) => {})
        cbwire.hook('element.initialized', (el, wire) => {})
        cbwire.hook('element.updating', (fromEl, toEl, wire) => {})
        cbwire.hook('element.updated', (el, wire) => {})
        cbwire.hook('element.removed', (el, wire) => {})
        cbwire.hook('message.sent', (message, wire) => {})
        cbwire.hook('message.failed', (message, wire) => {})
        cbwire.hook('message.received', (message, wire) => {})
        cbwire.hook('message.processed', (message, wire) => {})
    });
</script>
```

## Interacting With Wires

You can interact with your [Wires](/v2-1/essentials/creating-components), calling [Actions](/v2-1/essentials/actions), setting [Data Properties](/v2-1/essentials/properties), and more, using **cbwire.find** from within your [Wire Template](/v2-1/essentials/templates). Once you have a reference to the Wire, you can interact with it using the methods below.

```html
<script>
    document.addEventListener("livewire:load", function() {
        var thisWire = cbwire.find('#args._id#'); // args._id contains the id of our wire
    
        var count = thisWire.count; // gets the value of a data property called 'count'   
        
        thisWire.count = 5; // updates the values of a data property
    
        thisWire.increment(); // calls the increment action on our wire
        
        thisWire.addTask( 'someTask' ); // calls the addTask action and passes parameters 
        
        thisWire.call( 'increment' ); // same as increment call above 
    
        // On someEvent, console log
        thisWire.on( 'someEvent', function() {
            console.log('Got someEvent');
        } );  
        
        thisWire.emit('someEvent', 'foo', 'bar'); // emits someEvent and pass parameters
    } );
</script>
```


# Testing

Front-end testing of your UI Wires using a beautiful test API.

You can easily test your [Wires](/v2-1/essentials/creating-components) by extending `cbwire.models.BaseWireTest` and using our fluent testing API in your [TestBox](https://testbox.ortusbooks.com/) specs.

## Test Example

You can invoke your [Wires](/v2-1/essentials/creating-components) for testing by using `wire()`.&#x20;

```javascript
component extends="cbwire.models.BaseWireTest" {

    function run(){

        describe( "TaskList.cfc", function(){
	
	    it( "calling 'clearTasks' removes the tasks", function() {
        
                wire( "TaskList" )
                    // Sets our data properties
                    .data( "tasks", [ "task1" ] )
                    // Verifies output in our template rendering
                    .see( "<li>task 1</li>" )
                    // Runs the 'clearTasks' action
                    .call( "clearTasks" )
                    // Verifies updated template rendering
		    .dontSee( "<li>task 1</li>" );
		} );
	
	} );
    }
}
```

## Test Methods

### data

Set a [Data Property](/v2-1/essentials/properties) to the specified value.

```javascript
wire( "TaskList" )
    .data( "tasks", [ "task1", "task2" ] ) // one property at a time
    .data( { "tasks" : [ "task1", "task2" ] } ); // struct of properties
```

### computed

Set a [Computed Property](/v2-1/essentials/computed-properties) to the specified closure.

```javascript
wire( "TaskList" )
    .computed( "count", function() { return 3; } ) // one property at a time
    .computed( { "count" : function() { return 3; } } ); // struct of properties
```

### toggle

Toggles a [Data Property](/v2-1/essentials/properties) between true and false.

```javascript
wire( "TaskList" ).toggle( "showModal" );
```

### call

Calls an [Action](/v2-1/essentials/actions). Optional array of parameters can be provided.

```javascript
wire( "TaskList" ).call( "clearTasks" );
wire( "TaskList" ).call( "clearTasks", [ param1, param2 ] );
```

### emit

Emits an [Event](/v2-1/essentials/events) and fires any [Listeners](/v2-1/essentials/events#listeners) that are defined on the [Wire](/v2-1/essentials/creating-components). Optional array of parameters can be provided, which will be passed on to listeners.

```javascript
wire( "TaskList" ).emit( "addedTask" );
wire( "TaskList" ).emit( "addedTask", [ param1, param2 ] );
```

### see

Verifies a value can be found in the current [Template](/v2-1/essentials/templates) rendering. Otherwise, test fails.

```javascript
wire( "TaskList" ).see( "<h1>My Tasks</h1>" );
```

### dontSee

Verifies a value is not found in the current [Template](/v2-1/essentials/templates) rendering. Otherwise, test fails.

```javascript
wire( "TaskList" ).dontSee( "<h1>Someone Else's Tasks</h1> ");
```

### seeData

Verifies a [Data Property](/v2-1/essentials/properties) matches a specified value. Otherwise, test fails.

```javascript
wire( "TaskList" ).seeData( "tasksRemoved", true );
```

### dontSeeData

Verifies a [Data Property](/v2-1/essentials/properties) does not match a specified value. Otherwise, test fails.

```javascript
wire( "TaskList" ).dontSeeData( "tasksRemoved", true );
```


# Validation

[Wires](/v2-1/essentials/creating-components) include powerful validations that you can use to validate your [Data Properties](/v2-1/essentials/properties).

{% hint style="info" %}
Validations are provided by [cbValidation](https://coldbox-validation.ortusbooks.com/).
{% endhint %}

## Defining Constraints

You can define constraints within your wires using `this.constraints`.

```javascript
component extends="cbwire.models.Component"{

    this.constraints = {
        "task": { required: true }
    };
    
    // Data Properties
    data = {
        "task": ""
    };
}
```

## Validating

[Actions](/v2-1/essentials/actions) can validate against the defined constraints using `validate()` or `validateOrFail()`.

### validate

Returns a `ValidateResult` object.

```javascript
component extends="cbwire.models.Component"{
    // Action
    function addTask() {
        var result = validate(); // ValidateResult object
        
        if ( !result.hasErrors() ) {
            queryExecute( ... );
        }
    }
}
```

### validateOrFail

Silently fails and prevents further processing of the current [Action](/v2-1/essentials/actions).&#x20;

```javascript
component extends="cbwire.models.Component"{
    // Action
    function addTask() {
        validateOrFail();

        queryExecute( ... );        
    }
}
```

{% hint style="info" %}
With `validateOrFail(),`the error is gracefully caught and any further processing of the invoked action is prevented. The XHR response and re-rendered template are still returned. The actual errors themselves are available to the template using `args.validation`.&#x20;

If you need more granular control over the validation response, use `validate()` instead.
{% endhint %}

## Validation Manager

You can get a new *ValidationManager* object to work with, just call `getValidationManager()`;&#x20;

```javascript
component extends="cbwire.models.Component"{
    // Action
    function addTask() {
        var data = { "email": "cbwire@rocks.com" };

        var validationManager = getValidationManager();
        
        var result = validationManager.validate(
            target=data,
            constraints={
                "email": { required: true, type: "email" }
            }
        );
    }
}
```

## Displaying Errors

[Templates](/v2-1/essentials/templates) can access the *ValidationResults* object using `args.validation`. This includes helpful methods you can use for displaying error messages.

```html
<cfoutput>
<div>
    <input wire:model="task" type="text">
    <button wire:click="addTask">Add</button>
    
    <cfif args.validation.hasErrors( "task" )>
        <cfloop array="#args.validation.getAllErrors( "task" )#" index="error">
            <div>#error#</div>
        </cfloop>
    </cfif>
</div>
</cfoutput>
```


# File Uploads

## Basic File Upload

CBWIRE makes uploading and storing files easy.

Here's an example of a simple Wire that handles uploading a photo:

```javascript
component extends="cbwire.models.Component" {

    data = {
        "photo": "",
        "error": ""
    };
    
    function save() {
        // 'photo' is now an instance of FileUpload@cbwire
        if ( data.photo.getSize() > "100000" ) {
            data.error = "Photo upload too big!";
        } else {
            // Store our file locally
            fileWrite( expandPath( "./somewhere.jpg" ), data.photo.get() );
            
            // Delete our file from CBWIRE's temporary storage and reset 'photo' data property
            data.photo.destroy();
        }
    }
}
```

```html
<form wire:submit.prevent="save">
    File: <input type="file" wire:model="photo">
    <div><button type="submit">Save</button></div>
    
    <!--- Show thumbnail --->
    <cfif isObject( args.photo ) and args.photo.isImage()>
        <div><img src="#args.photo.getPreviewURL()#"></div>
    </cfif>
    
    <cfif len( args.error ) >
        <div class="error">#args.error#</div>
    </cfif>
</form>
```

Handling file inputs is no different than handling any other input type with CBWIRE. Add `wire:model` to the `<input>` tag and CBWIRE will take care of the rest.

There are several things happening under the hood to make file uploads work:

1. CBWIRE makes an initial request to the server to get a temporary "signed" upload URL.
2. Once the URL is received, JavaScript then does the actual "upload" to the signed URL, storing the upload in a temporary directory designated by CBWIRE and returning the new temporary file's unique hash ID.
3. Once the file is uploaded, and the unique hash ID is generated, CBWIRE makes a final request to the server, telling it to "set" the desired data property to the upload file as an instance of FileUpload ( see below ).
4. Now the data property (in this case `photo` ) is set to an instance of `FileUpload@cbwire` and is ready to be stored or validated at any point.

## FileUpload Object

CBWIRE will automatically upload your files and set your associated data property to an instance of `FileUpload@cbwire`. Here are some of the methods you can use that can get quite helpful.

| Method                    | Description                                                                                                                                                                          |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| getComp()                 | Returns an instance of your current Wire.                                                                                                                                            |
| getParams()               | Returns any params that are passed in, including the data property name.                                                                                                             |
| get()                     | Returns the contents of the file uploaded.                                                                                                                                           |
| getBase64()               | Returns base64 encoded string of the file.                                                                                                                                           |
| getBase64Src()            | Returns a base64 src string that can be used with \<img tag>. It is recommended to use this carefully because with larger objects, this can slow down CBWIRE response times.         |
| getTemporaryStoragePath() | Returns the temporary storage path where the file is stored by CBWIRE.                                                                                                               |
| getMetaPath()             | Returns the file path to meta information of the uploaded file. You can find additional details here like the name of the file when it was uploaded, the client file extension, etc. |
| getMeta()                 | Returns all captured meta information on the file upload.                                                                                                                            |
| getSize()                 | Returns the size of the file upload.                                                                                                                                                 |
| getMimeType()             | Returns the mime type of the file upload.                                                                                                                                            |
| isImage()                 | Returns true if this is an image.                                                                                                                                                    |
| getPreviewURL()           | Provides a URL to preview the file uploaded. It only works with image uploads.                                                                                                       |
| destroy()                 | Deletes the temporary storage and metadata of the file upload. It's essential to use this after storing the file upload in permanent storage.                                        |

## Loading Indicators

You can display a loading indicator scoped to the file input during upload like so:

```html
<input type="file" wire:model="photo">
 
<div wire:loading wire:target="photo">Uploading...</div>
```

The "Uploading..." message will be shown as the file is uploading and then hidden when the upload is finished.

This works with the entire [Loading States API](/v2-1/template-features/loading-states).


# Query String

It can be useful at times to update the browser's query string when your [Wire's ](/v2-1/essentials/creating-components)state changes.

## Example

Let's say you are building a [Wire](/v2-1/essentials/creating-components) to search articles, and want the query string to reflect the current search value like so:

```
https://yourapp.com/search-articles?search=some+string
```

This way, when a user hits the back button or bookmarks the page, you can get the initial state out of the query string rather than resetting the [Wire](/v2-1/essentials/creating-components) every time.

You can add a `queryString` variable to your [Wires](/v2-1/essentials/creating-components) and CBWIRE will update the query string every time the property value changes and also update the property when the query string changes.

```javascript
component extends="cbwire.models.Component" {

    data = {
        "search": ""
    };
    
    queryString = [ "search" ];
}
```

```html
<div>
    <input wire:model="search" type="search" placeholder="Search articles...">
</div>
```


# Redirecting

Similar to ColdBox, you can relocate users using relocate.

You can redirect users in your [Actions](/v2-1/essentials/actions) using `relocate()`.

## relocate

Redirects a user to a different URI, URL, or event.

```javascript
component extends="cbwire.models.Component"{

    // Action
    function clickButton() {
        // Relocate to Google
        relocate( url="https://www.google.com" );
        
        // Relocate using URI
        relocate( uri="/some/relative/path" );
        
        // Relocate using event and set variables in Flash Ram
        relocate( event="example.index", persistStruct={
            success: true
        } );
    }

}
```

CBWIRE's relocate() method signature is nearly identical to ColdBox's internal relocate() method, with the exception that status codes cannot be set. Otherwise, most of the arguments that ColdBox accepts can be used.

```javascript
/**
 * Relocate user browser requests to other events, URLs, or URIs.
 *
 * @event             The name of the event to relocate to, if not passed, then it will use the default event found in your configuration file.
 * @queryString       The query string or a struct to append, if needed. If in SES mode it will be translated to convention name value pairs
 * @addToken          Wether to add the tokens or not to the relocation. Default is false
 * @persist           What request collection keys to persist in flash RAM automatically for you
 * @persistStruct     A structure of key-value pairs to persist in flash RAM automatically for you
 * @ssl               Whether to relocate in SSL or not. You need to explicitly say TRUE or FALSE if going out from SSL. If none passed, we look at the even's SES base URL (if in SES mode)
 * @baseURL           Use this baseURL instead of the index.cfm that is used by default. You can use this for SSL or any full base url you would like to use. Ex: https://mysite.com/index.cfm
 * @postProcessExempt Do not fire the postProcess interceptors, by default it does
 * @URL               The full URL you would like to relocate to instead of an event: ex: URL='http://www.google.com'
 * @URI               The relative URI you would like to relocate to instead of an event: ex: URI='/mypath/awesome/here'
 *
 * @return void
 */
function relocate(
	event                = "",
	queryString          = "",
	boolean addToken     = false,
	persist              = "",
	struct persistStruct = structNew()
	boolean ssl,
	baseURL                   = "",
	boolean postProcessExempt = false,
	URL,
	URI
)
```


# Dependency Injection

Just as with ColdBox, you can inject your dependencies using WireBox.

## WireBox

[Wires](/v2-1/essentials/creating-components) have [WireBox](https://wirebox.ortusbooks.com/) available for injecting dependencies such as service objects, session storage, you name it!

```javascript
component extends="cbwire.models.Component" {

    // Property injection
    property name="storage" inject="cbfs:disks:temp";

    // Setter injection
    function setStorage() inject="cbfs:disks:temp" {};

    // Actions
    function someAction() {
        // Use the storage object
        storage.create( "log.txt", "CBWIRE rocks!" );
        // Use getInstance() to get objects.
        var defaultStorage = getInstance( "cbfs:disks:default" ); 
    }

}
```

## onDIComplete

If you want to act immediately after dependency injection has been completed, you can define an `onDIComplete` method.

```javascript
component extends="cbwire.models.Component" {

    property name="storage" inject="cbfs:disks:temp";

    function onDIComplete(){
        storage.create( "log.txt", "Dependency Injection Complete!" );
    }

}
```


# Directives

CBWIRE's powerful directives allow you to listen for client side events, invoke actions, bind to data properties, and more.

## Core Directives

The following Directives can be added to your [Templates](/v2-1/essentials/templates) and instruct CBWIRE how and when to update the [Wire](/v2-1/essentials/creating-components).

### wire:key

```html
<div wire:key="foo"></div>
```

Define a key name `foo` for the element. This provides a reference point for the Livewire DOM diffing system. Useful for adding/removing elements and keeping track of lists.

### wire:click

```html
<button wire:click="foo">...</button>

<a href="" wire:click.prevent="foo">Click here</a>
```

Listens for a `click` event and invokes the `foo` [Action](/v2-1/essentials/actions).

{% hint style="info" %}
You will want to add the .prevent [modifier](#event-modifiers) to ensure that the browser doesn't follow the link.
{% endhint %}

### wire:click.prefetch

```html
<button wire:click.prefetch="foo">...</button>
```

Listens for a `mouseEnter` event and then prefetches the result of the `foo` [Action](/v2-1/essentials/actions). If the element is then clicked, it will swap in the prefetched result without any extra request. If it's not clicked, the cached results will be thrown away.

### wire:submit

```html
<form wire:submit.prevent="someAction">
    <button type="submit">Submit Form</button>
</form>
```

Listeners for a `submit` event on a form.

{% hint style="info" %}
You will want to add the .prevent [modifier](#event-modifiers) to ensure that the browser doesn't submit the form.
{% endhint %}

### wire:keydown

```html
<input wire:keydown="foo" type="text">
```

Listens for a `keyDown` event and invokes the `foo` [Action](/v2-1/essentials/actions).

### wire:keydown.enter

```html
<input wire:keydown.enter="foo" type="text">
```

Listens for a `keyDown` event when the user hits enter and invokes the `foo` [Action](/v2-1/essentials/actions).

### wire:foo

```html
<select wire:foo="bar"></select>
```

Listens for a `foo` event and invokes the `bar` [Action](/v2-1/essentials/actions).&#x20;

{% hint style="success" %}
You can listen to any JS event, not just those defined by Livewire.
{% endhint %}

### wire:model

```html
<input wire:model="foo" type="text">
```

Provided you have `data[ "foo" ]` defined in your [Data Properties](/v2-1/essentials/properties), this creates a one-to-one model binding. Any time the element is updated, the value is synchronized.

### wire:model.debounce

```html
<input wire:model.debounce.1s="foo" type="text">
<input wire:model.debounce.500ms="foo" type="text">
```

The same as `wire:model="foo"` except that all input events to the element will be debounced for the specified duration. Defaults to 150 milliseconds. Useful for reducing XHR background requests during user input. You can set the milliseconds value to any numeric value.

### wire:model.defer

```html
<input wire:model.defer="foo" type="text">
```

Creates a one-to-one model binding with `data[ "foo" ]` in your [Data Properties](/v2-1/essentials/properties) but defers any XHR updates until an [Action](/v2-1/essentials/actions) is performed. Useful for reducing XHR requests.

### wire:model.lazy

```
<input wire:model.lazy="foo" type="text">
```

Creates a one-to-one model binding with `data[ "foo" ]` in your [Data Properties](/v2-1/essentials/properties) but will not perform an XHR updates until an `onBlur` event is emitted. Useful for reducing XHR requests.

{% hint style="success" %}
If your input field does not require immediate updating ( such as for instant form validation), we highly recommended you used the lazy modifier to reduce the number of XHR requests .
{% endhint %}

### wire:poll

```html
<div wire:poll></div>
<div wire:poll.5s></div>
<div wire:poll.5000ms></div>
<div wire:poll.5s="fooMethod"></div>
```

Performs an XHR request to re-render the elements based on a set interval. An interval can be specified in both seconds or milliseconds. You can also specify an [Action](/v2-1/essentials/actions) that you want to invoke. [*See Polling*](/v2-1/template-features/polling)

### wire:init

```html
<div wire:init="foo"></div>
```

Invokes the `foo` [Action](/v2-1/essentials/actions) on your [Wire](/v2-1/essentials/creating-components) immediately after it's rendered on the page.

### wire:loading

```html
<span wire:loading><img src="spinner.gif"></span>
```

Hides the HTML element by default and makes it visible when XHR requests are performed.

### wire:loading.class

```html
<div wire:loading.class="highlight"></div>
```

Adds the `foo` class to the HTML element while XHR requests are in transit.

### wire:loading.class.remove

```html
<div wire:loading.class.remove="highlight" class="highlight"></div>
```

Removes the `foo` class from the HTML element while XHR requests are in transit.

### wire:loading.attr

```html
<button wire:loading.attr="disabled">...</button>
```

Adds the `disabled="true"` attribute while XHR requests are in transit.

### wire:dirty

Hides the HTML element by default and makes it visible when the element's state has changed since the latest XHR request.

```html
<div wire:dirty="foo">...</div>
```

### wire:dirty.class

```html
<div wire:dirty.class="highlight">...</div>
```

Adds the `foo` class to the HTML element when the element's state has changed since the latest XHR request.

### wire:dirty.class.remove

```html
<div wire:dirty.class.remove="highlight" class="highlight">...</div>
```

Removes the `foo` class from the HTML element when the element's state has changed since the latest XHR request.

### wire:dirty.attr

```html
<button wire:dirty.attr="disabled">...</div>
```

Adds the `disabled="true"` attribute when the element's state has changed since the latest XHR request. Used in addition to `wire:target`.

### wire:target

```html
<button wire:dirty.attr="disabled" wire:target="foo">...</div>
```

Provides scoping for `wire:loading` and `wire:dirty` references, scoped to a specific [Action](/v2-1/essentials/actions).

### wire:ignore

```html
<div wire:ignore></div>
```

Instructs Livewire to not update the element or any child elements when updating the DOM. Useful when using third-party JavaScript libraries.

### wire:ignore.self

```html
<div wire:ignore.self></div>
```

Instructs Livewire to not update the element but DOES allow updates to any child elements when updating the DOM.

### wire:offline

*See* [*Offline State*](/v2-1/template-features/offline-state)

## Event Modifiers

CBWIRE Directives sometimes offer "modifiers" to add extra functionality to an event. Here are the available modifiers that can be used with any event.

| Modifier       |                                                                                                                                                                                                                                  |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| stop           | Equivalent of `event.stopPropagation()`                                                                                                                                                                                          |
| prevent        | Equivalent of `event.preventDefault()`                                                                                                                                                                                           |
| self           | Only triggers an action if the event was triggered on itself. This prevents outer elements from catching events that were triggered from a child element. (Like often in the case of registering a listener on a modal backdrop) |
| debounce.300ms | Adds an Xms debounce to the handling of the action.                                                                                                                                                                              |

```html
<a href="" wire:click.prevent="someAction">Click here</a>
```

### Keydown Modifiers

To listen for specific keys on **keydown** events, you can provide the name of the key as a modifier. You can use any valid key names exposed via [KeyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) as modifiers by converting them to kebab-case.

Here is a quick list of some common ones you may need:

| Native Browser Event | Livewire Modifier |
| -------------------- | ----------------- |
| Backspace            | backspace         |
| Escape               | escape            |
| Shift                | shift             |
| Tab                  | tab               |
| ArrowRight           | arrow-right       |

```html
<input wire:keydown.page-down="foo">
```

In the above example, the foo [Action](/v2-1/essentials/actions) will only be called if `event.key` is equal to 'PageDown'.


# Loading States

Help website users during wait times using Loading States.

[Actions](/v2-1/essentials/actions) may involve a long-running process (such as completing a cart checkout) and HTML may not re-render instantly. You can help your users during the wait using Loading States. Loading States allow you to show/hide elements, add/remove classes, or toggle HTML attributes until the server responds.

{% hint style="success" %}
Loading States can make your apps feel much more responsive and user-friendly.
{% endhint %}

## Toggling Elements

Let's look at an action that takes too long.

```javascript
component extends="cbwire.models.Component"{

    function addTask(){
        sleep( 5000 ); // Optimize this code yo!
    }

}
```

We can annotate our `<div>` with `wire:loading` to display *Adding Task* while the checkout action is running.

```xml
<div>
    <button wire:click="addTask">Add Task</button>

    <div wire:loading>
        Adding Task...
    </div>
</div>
```

After the action completes, the *Adding Task...* output will disappear. :wave:&#x20;

## Toggling Attributes

```xml
<div>
    <button wire:click="addTask" wire:loading.attr="disabled">
        Add Task
    </button>
</div>
```

## Targeting Specific Actions

You can target a specific action so that the element is only visible is a specific action is loading using `wire:target`.

```html
<div>
    <button wire:click="addTask">Add Task</button>
 
    <div wire:loading wire:target="addTask">
       Adding task...
    </div>
</div>
```

## Delaying

If you want to avoid flickering because loading is very fast, you can add a `.delay` modifier, and it will only show up if loading takes longer than `200ms`.

```html
<div wire:loading.delay>...</div>
```

If you wish, you can customize the delay duration with the following modifiers:

```xml
<div wire:loading.delay.shortest>...</div> <!-- 50ms -->
<div wire:loading.delay.shorter>...</div>  <!-- 100ms -->
<div wire:loading.delay.short>...</div>    <!-- 150ms -->
<div wire:loading.delay>...</div>          <!-- 200ms -->
<div wire:loading.delay.long>...</div>     <!-- 300ms -->
<div wire:loading.delay.longer>...</div>   <!-- 500ms -->
<div wire:loading.delay.longest>...</div>  <!-- 1000ms -->
```

## Display Property

Loading State elements are set with a CSS property of `display: inline-block;` by default. You can override this behavior by using various directive modifiers.

```xml
<div wire:loading.flex>...</div>
<div wire:loading.grid>...</div>
<div wire:loading.inline>...</div>
<div wire:loading.table>...</div>
```

## Hiding

If you would like to display an element **except** during a loading state, you can apply the `wire:loading.remove` directive.

```xml
<div>
    <button wire:click="addTask">Add Task</button>

    <div wire:loading.remove>
        Click 'Add Task'
    </div>
</div>
```


# Polling

Poll for state changes based on a specified interval without page refreshes. Hot dog!

You can add a `wire:poll` directive to your elements to poll for changes using a set interval. The default interval is set to poll every *2 seconds*.

```xml
<div wire:poll></div>
```

You can append a different interval time to your directive as well.

```xml
<div wire:poll.5s> <!-- poll every 5 seconds --> </div>
```

{% hint style="success" %}
Polling for changes over AJAX can be a resonable alternative to strategies such as Pusher or WebSockets.&#x20;
{% endhint %}

## Method Invocation

If you would like to invoke a method during each poll interval, you can do so by specifying a method name.

```xml
<div wire:poll="refreshTasks"></div>
```

```javascript
component extends="cbwire.models.Component" {
    
    function refreshTasks() {}
}
```

## Cancel Polling

If you want stop polling, you can simply no longer render the HTML element that has the `wire:poll` directive.

```html
<cfif args.shouldPoll>
    <div wire:poll="refreshTasks"></div>
<cfelse>
    <div><!-- No more polling --></div>
</cfif>
```


# Prefetching

Prefetch state changes when the user mouses over an HTML element. Fantastico!

You can prefetch an [Action's](/v2-1/essentials/actions) results on mouseOver using the `.prefetch` modifier.&#x20;

```xml
<div>
    <button wire:click.prefetch="togglePreview">Show Preview</button>

    <cfif args.showPreview>
        <!--- Preview goes here --->
    </cfif>
</div>
```

```javascript
component extends="cbwire.models.Component"{

    data = {
        "showPreview": false
    };

    function togglePreview(){
        data.showPreview = true;
    }
}
```

{% hint style="success" %}
In the example here, the `togglePreview` action will be prefetched and invoked when the user mouses over the button. The results of the fetch are not displayed until the user clicks the 'Show Preview' button.
{% endhint %}

{% hint style="warning" %}
Prefetching works well for actions that do not perform any side effects, such as mutating session data or writing to a database. If the action you are "pre-fetching" does have side effects, you may encounter unpredictable results.
{% endhint %}


# Offline State

Toggle UI elements when the user is offline or online. Groovy!

You can use `wire:offline` to display elements when Livewire detects that the user is offline.

```html
<div wire:offline><!-- Oh no, you're offline --></div>
```

You can also append `.class` to your `wire:offline` [Directive](/v2-1/template-features/directives) and specify a CSS class to toggle when the user is offline.

```html
<div wire:offline.class="online" class="online"></div>
```

Use `.remove` to specify classes you want to be removed when offline.

```html
<div wire:offline.class.remove="im-online" class="im-online"></div>
```


# Defer Loading

Call an action immediately once your Wire is first rendered.

You can use the `wire:init` [Directive](/v2-1/template-features/directives) to execute an action as soon as your component is initially rendered.

{% hint style="success" %}
This can be helpful in cases where you don't want to hold up the entire page load, but want to load some data immediately after the page load.
{% endhint %}

```html
<div wire:init="loadTasks">
    <ul>
        <cfloop array="#args.tasks#" index="task">
            <li>#task#</li>
        </cfloop>
    </ul>
</div>
```

```javascript
component extends="cbwire.models.Component" {

    property name="taskService" inject="TaskService@myapp";
    
    data = {
        "tasks": []
    };
    
    function loadTasks(){
        data.tasks = taskService.asMemento().get();
    }
    
}
```


# Dirty State

Track changes to Data Properties and display changes in your UI instantly.

There are cases where it may be helpful to provide feedback that content has changed and is not yet in sync with the back-end. For input that uses `wire:model`, or `wire:model.lazy,` you can display that a field is 'dirty' until CBWIRE has fully updated.

### Toggle Dirty Elements

Adding the `.class` modifier allows you to add a class to the element when dirty.

```html
<div>
    <input wire:dirty.class="border-red-500" wire:model.lazy="foo">
</div>
```

You can perform the inverse and remove classes by adding the `.remove` modifier.

```html
<div>
    <input wire:dirty.class.remove="bg-green-200" class="bg-green-200" wire:model.lazy="foo">
</div>
```

### Toggle Elements

The default behavior of the `wire:dirty` directive without modifiers is that the element is hidden until dirty. This can create a paradox if used on the input itself, but like loading states, the `dirty` directive can be used to toggle the appearance of other elements using `wire:target.`

In this example, the `span` is hidden by default and only visible when the input element is dirty.

```html
<div>
    <span wire:dirty wire:target="foo">Updating...</span>
    <input wire:model.lazy="foo">
</div>
```

### Toggle Other Elements

Use the class and attribute modifiers in the same way for referenced elements.

```html
<div>
    <label wire:dirty.class="text-red-500" wire:target="foo">Full Name</label>
    <input wire:model.lazy="foo">
</div>
```


# ContentBox CMS

You can use CBWIRE alongside ContentBox to build modernize, reactive applications with a powerful CMS included.

[ContentBox](https://contentbox.ortusbooks.com/) is a professional open source *hybrid* modular CMS (Content Management System) that allows you to easily build websites, blogs, wikis, complex web applications and even power mobile or cloud applications. Built with a secure and flexible modular core, designed to scale, and combined with world-class support, ContentBox will get your projects out the door in no time.

## Installation

{% hint style="info" %}
You need to install CBWIRE version 2.3.3 or later in order to be able to use CBWIRE and ContentBox.
{% endhint %}

In the root of your ContentBox application, install CBWIRE using [CommandBox](https://commandbox.ortusbooks.com/). The example below installs the latest bleeding-edge version.

```
box install cbwire@be
```

{% hint style="info" %}
Once installed, you will need to restart your app using ?fwreinit=\[your secret key].
{% endhint %}

{% hint style="warning" %}
Ensure that CBWIRE is installed under **/modules/cbwire** from the root of your project. It should be installed there by default. Installing CBWIRE elsewhere can cause errors within a ContentBox application.
{% endhint %}

## Theme Integration

**You will need to use a custom theme in order to integrate with CBWIRE**.

If you are wanting to use a theme that is included with ContentBox or one that you've pulled down from ForgeBox, you can copy the theme code over to the folder **modules\_app/contentbox-custom/\_themes**.

Once CBWIRE is installed, you should have access to the three core included methods and should be able to reference these within your layout and theme templates.

* **wireStyles()** - Pulls in required styling for CBWIRE
* **wireScripts()** - Pulls in required JavaScript assets for CBWIRE/Livewire
* **wires()** - Includes a [Wire](/v2-1/essentials/creating-components) (reactive UI element) you create

In your theme layout, you need to place `wireStyles()` within your \<head> tags, `wireScripts()` before the end of \</body>, and you can call `wire()` to include your reactive UI Wires where needed.

```html
<!--- modules_app/contentbox-custom/_themes/cbwireTheme/layouts/blog.cfm --->
<cfoutput>
<!--- Global Layout Arguments --->
<cfparam name="args.print" default="false">
<cfparam name="args.sidebar" default="true">

<!DOCTYPE html>
<html lang="en">
<head>
	<!--- Page Includes --->
	#cb.quickView( "_blogIncludes" )#

	<!--- ContentBoxEvent --->
	#cb.event( "cbui_beforeHeadEnd" )#

	<!--- PULL IN CBWIRE STYLING --->
	#wireStyles()#
</head>
<body>
	<!--- ContentBoxEvent --->
	#cb.event( "cbui_afterBodyStart" )#

	<!--- Header --->
	#cb.quickView( '_header' )#

	<!--- ContentBoxEvent --->
	#cb.event( "cbui_beforeContent" )#

	<!--- Main View --->
	#cb.mainView( args=args )#
	
	<!--- INCLUDE REACTIVE NEWSLETTER SIGNUP COMPONENT --->
	#wire( "NewsletterSignup", {
		validate: true
	} )#

	<!--- ContentBoxEvent --->
	#cb.event( "cbui_afterContent" )#

	#cb.quickView( view='_footer' )#

	<!--- ContentBoxEvent --->
	#cb.event( "cbui_beforeBodyEnd" )#

	<!--- PULL IN CBWIRE JAVASCRIPT ASSETS --->
	#wireScripts()#
</body>
</html>
</cfoutput>
```

You can also reference the wire() method within your views.

```html
<!--- modules_app/contentbox-custom/_themes/cbwireTheme/views/index.cfm --->
<div class="row">
    <div class="col-12">
        #wire( "ContactForm" )#
    </div>
</div>
```


# Turbo

Remove full-page reloads from your applications and create single-page applications with ease using Turbo.

Turbo is an open-source library that accelerates links and form submissions by negating the need for full page reloads. With Turbo, you get all the following included:

* Links and form submissions are performed in the background using AJAX instead of performing full page reloads
* Browse history management, so clicking the back and forward buttons in the browser work as expected
* Internal caching that improves perceived performance by showing temporary previews during network requests and while the page is updated
* [Built-in progress bar](#displaying-progress)
* [Pre-load Links](#undefined)
* And much more!

CBWIRE and Turbo together allow you to quickly build single-page applications in record time.

{% hint style="success" %}
For additional information on how Turbo can be used and configured, please see <https://turbo.hotwired.dev/>
{% endhint %}

## Enabling Turbo

You can enable Turbo with the **enableTurbo** [configuration setting](/v2-1/essentials/configuration), which automatically wires up everything needed to start using Turbo. Once enabled, links and form submissions will automatically be performed in the background via AJAX instead of performing full page reloads.&#x20;

You can alternatively perform a [manual installation](#manual-installation) of Turbo instead.

```javascript
// File: ./config/ColdBox.cfc
component{
    function configure() {
        moduleSettings = {
            "cbwire" = {
                "enableTurbo": true
            }
        };
     }
}

```

## Manual Installation

{% hint style="info" %}
Use the manual installation when you want more control over where Turbo is included within your HTML.
{% endhint %}

### npm

You can install Turbo by running the following `npm` command in the root of your project.

```bash
npm i @hotwired/turbo
```

Then you can require or import Turbo.

```javascript
import * as Turbo from "@hotwired/turbo"
```

### Skypack

To avoid manual installation, there is also a [Skypack](https://www.skypack.dev/view/@hotwired/turbo) available which you can add to the \<head>\</head> of your layout.

```html
<script type="module">
    import hotwiredTurbo from 'https://cdn.skypack.dev/@hotwired/turbo';
</script>
```

### Livewire/Turbo Plugin

For Turbo to work properly with Livewire (and therefore CBWIRE), you will also need to include the Turbo plugin below your `wireScripts()` call in your layout.

```javascript
    #wireScripts()#
    <script src="https://cdn.jsdelivr.net/gh/livewire/turbolinks@v0.1.x/dist/livewire-turbolinks.js" data-turbolinks-eval="false" data-turbo-eval="false"></script>
</body>
```

{% hint style="info" %}
Note: You MUST have either the `data-turbolinks-eval="false"` or `data-turbo-eval="false"` attributes added to the script tag (having both won't hurt).
{% endhint %}

## Displaying Progress&#x20;

During Turbo navigation, the browser will not display its native progress indicator. Turbo installs a CSS-based progress bar to provide feedback while issuing a request.

The progress bar is enabled by default. It appears automatically for any page that takes longer than 500ms to load.

The progress bar is a `<div>` element with the class name `turbo-progress-bar`. Its default styles appear first in the document and can be overridden by rules that come later.

For example, the following CSS will result in a thick green progress bar:

```css
.turbo-progress-bar {
    height: 5px;
    background-color: green;
}
```

In your layout file, you can include the progress bar like so:

```html
<!-- ./layouts/Main.cfm -->
<cfoutput>
<html>
    <head>
        <title>Turbo Page</title>
        #wireStyles()#
    </head>
    <body>
        <div class="turbo-progress-bar"></div>
        <div class="mainContent">
            Some content here
        </div>
        #wireScripts()#
    </body>
</html>
</cfoutput>
```

## Preload Links into Turbo's Cache

Preload links into Turbo Drive’s cache using **data-turbo-preload**.

```html
<a href="/" data-turbo-preload>Home</a>
```

This will make page transitions feel lightning fast by providing a preview of a page even before the first visit. Use it to preload the most important pages in your application.&#x20;

{% hint style="warning" %}
Avoid over usage, as it will lead to loading content that is not needed.
{% endhint %}


# AlpineJS

Beautifully integrate your client-side JavaScript and CBWIRE using AlpineJS.

Many page interactions don't warrant a full server roundtrip, such as toggling a modal or a hidden element. In these instances, we recommend using [AlpineJS](https://alpinejs.dev/).

{% hint style="info" %}
AlpineJS allows you to add JavaScript behavior directly into your markup in a declarative way. If you are familiar with VueJS, Alpine should feel similar.
{% endhint %}

## Installation

```html
<head>
    <script src="//unpkg.com/alpinejs" defer></script>
    <!-- The "defer" attribute is important to ensure Alpine waits for CBWIRE to load first. -->
</head>
```

For more installation information, visit the [Alpine Docs](https://alpinejs.dev/).

## Templates

Below is an example of using [AlpineJS](https://alpinejs.dev/) to toggle a list on the page.

```html
<div>
    <div x-data="{ open: false }">
        <button @click="open = true">Show More...</button>
 
        <ul x-show="open" @click.away="open = false">
            <li><button wire:click="archive">Archive</button></li>
            <li><button wire:click="delete">Delete</button></li>
        </ul>
    </div>
</div>
```

## Entangle: Share State Between CBWIRE And AlpineJS

{% hint style="warning" %}
You need CBWIRE v2.3.6 or greater to use entangle.
{% endhint %}

CBWIRE has a powerful *entangle()* method that allows you to "entangle" a CBWIRE and AlpineJS data property. With entanglement, both client-side and server-side properties are instantly synchronized, regardless of whether the value was changed server-side in CFML or client-side using JavaScript.

{% hint style="success" %}
This provides data model binding both client-side and server-side.
{% endhint %}

Consider this simple Counter [Wire](/v2-1/essentials/creating-components):

```javascript
// wires/Counter.cfc
component extends="cbwire.models.Component" {

    data = {
        "counter": 0
    };

    function increment() {
        data.counter += 1;
    }
}
```

And now, our template:

<pre class="language-html"><code class="lang-html"><strong>&#x3C;!--- views/wires/counter.cfm --->
</strong><strong>&#x3C;cfoutput>
</strong>    &#x3C;div x-data="{ counter: #entangle( 'counter' )# }">
        &#x3C;div>CBWIRE value: #args.counter#&#x3C;/div>
        &#x3C;div>AlpineJS value: &#x3C;span x-html="counter">&#x3C;/span>&#x3C;/div>
        
        &#x3C;button
            wire:click="increment"
            type="button">Increment with CBWIRE&#x3C;/button>
        
        &#x3C;button
            @click="counter += 1"
            type="button">Increment with AlpineJS&#x3C;/button>
    &#x3C;/div>
&#x3C;/cfoutput>
</code></pre>

We define an AlpineJS property named *counter and* then call the built-in CBWIRE method *entangle()*, passing it the name of the server-side data property we want to bind with.

```html
<div x-data="{ counter: #entangle( 'counter' )# }">
```

Next, we are incrementing our Counter in two separate ways:

* Incrementing the counter by calling the increment [Action](/v2-1/essentials/actions) using CBWIRE
* Incrementing the AlpineJS property *counter* value in JavaScript, triggering an immediate update to the server and re-rendering of the Counter [Wire](/v2-1/essentials/creating-components).

```html
<button wire:click="increment" type="button">Increment with CBWIRE</button>
<button @click="counter += 1" type="button">Increment with AlpineJS</button>
```

Updating CBWIRE server-side on every AlpineJS property change is optional. You can also delay the server-side updates until the next CBWIRE request that goes out by chaining a *.defer* modifier like so.

```html
<div x-data="{ counter: #entangle( 'counter' )#.defer }">
```


# Inline Scripts

You can listen for livewire:load and place any JavaScript there.

We recommend you use [AlpineJS](https://alpinejs.dev/) for most of your JavaScript needs, but you can use `<script>` tags directly inside your [Templates](/v2-1/essentials/templates).

```html
<div>
    <!--- Your component's template --->
    <script>
        document.addEventListener('livewire:load', function () {
            // Your JS here.
        })
    </script>
</div>
```

{% hint style="warning" %}
Your scripts will be run only once upon the first render of the component. If you need to run a JavaScript function later, you can emit the [Event](/v2-1/essentials/events) from the component and listen to it in JavaScript.
{% endhint %}


# Introduction

CBWIRE is a ColdBox module that helps you build modern, reactive CFML applications in record time - without using much JavaScript or building backend APIs. Become a web development hero with CBWIRE!

<figure><img src="https://1609386017-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MXiNYsHUJlavmFh1GPp%2F-MdyzqNxu6GJtqIN1E04%2F-Mdz-Lp0mrS43T5i6qGn%2Flogo.png?alt=media&amp;token=c30d87f7-f915-4cf1-9ee8-f8e9b27c5493" alt=""><figcaption></figcaption></figure>

## Your First Component

Download and install [CommandBox](https://www.ortussolutions.com/products/commandbox). From your CLI, start CommandBox by typing 'box'. Then run the following:

```
mkdir cbwire-playground --cd
coldbox create app
install cbwire@be
server start
```

Let's insert a counter element into our Main layout using **wire( "Counter" )***.*

```markup
<!--- ./layouts/Main.cfm --->
<cfoutput>
<!doctype html>
<html>
<head>
    <!--- CBWIRE CSS --->
    #wireStyles()#
</head>
<body>
    <!--- INSERT A COUNTER HERE --->
    #wire( "Counter" )#

    <!--- CBWIRE JS --->
    #wireScripts()#
</body>
</html>
</cfoutput>
```

Let's define our Counter component using the path **./wires/Counter.cfm**.&#x20;

```html
<cfscript>
    // Data properties
    data = {
        "counter": 0 // default value
    };
    
    // Actions
    function increment() {
        data.counter += 1;
    }
</cfscript>

<!--- Our template --->
<cfoutput>
    <div>
        <div>Count: #counter#</div>
        <button wire:click="increment">+</button>
    </div>
</cfoutput>
```

You now have a reactive counter that increments when you click the plus button without any page refreshing or writing JavaScript<mark style="color:blue;">!</mark> 🤯

![](https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEWvXvmxEDxwnAJzKYkxz%2Fuploads%2FPESERLoILEJOeO4yXCCn%2F2022-02-08%2016.02.25.gif?alt=media\&token=7846eb9)

## What!? How?

1. CBWIRE automatically processes the HTML template, data properties, and actions of our component, then displays the component with its initial settings (which begin at 0).
2. When a user clicks a button, CBWIRE initiates an XMLHTTPRequest (XHR) to communicate with the server.
3. CBWIRE captures this XMLHTTPRequest and triggers the 'increment()' action, leading to an update in our data property.
4. Following this, CBWIRE updates the HTML template and includes this revised HTML in the XMLHTTPRequest response.
5. CBWIRE monitors any state changes and employs JavaScript and DOM comparison techniques to refresh the display on the screen.

## Awesome, right?

* We developed a responsive counter using just one file: wires/Counter.cfm.
* We avoided writing any JavaScript code.
* We didn't need to create an API.
* There was no need for page refreshes.
* We skipped using webpack or dealing with JavaScript compilation.
* We stayed entirely within the CFML environment. :nerd:

CBWIRE is transforming the way we build CFML applications, and we think you're going to love it too!

## Credits

CBWIRE uses [Livewire](https://laravel-livewire.com/) for its client-side functionality and DOM diffing and wouldn't exist without the awesome work of [Caleb Porzio](https://twitter.com/calebporzio) ( creator of [Livewire](https://laravel-livewire.com/), [Alpine.js](https://github.com/alpinejs/alpine) ).

The CBWIRE module for ColdBox is written and maintained by [Grant Copley](https://twitter.com/grantcopley), [Luis Majano](https://twitter.com/lmajano), and [Ortus Solutions](https://www.ortussolutions.com/).

## Project Support

Please consider becoming one of our lovingly esteemed [Patreon supporters](https://www.patreon.com/ortussolutions).


# Getting Started

Every journey starts somewhere.

## Requirements

* Adobe ColdFusion 2018+ or Lucee 5+
* ColdBox 6+

## Installation

Install [CommandBox](https://www.ortussolutions.com/products/commandbox).

Within the root of your project, run:

```bash
box install cbwire@3
```

If you want the latest bleeding edge, run:

```bash
box install cbwire@be
```

## Layout Setup

CBWIRE requires some lightweight CSS and JavaScript to be added to your ColdBox layout.

You can have CBWIRE do this for you by enabling the **autoInjectAssets** [Configuration](/3.x/configuration) property in your config/ColdBox.cfc file.

```javascript
// config/ColdBox.cfc
moduleSettings = {
    "cbwire" : {
        "autoInjectAssets": true
    }
};
```

You can also manually add the references by calling **wireStyles()** and **wireScripts()** in your layout file.

```html
<!--- ./layouts/Main.cfm --->
<cfoutput>
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>My Page</title>
        <!--- CBWIRE CSS --->
        #wireStyles()#
    </head>
    <body>
        <!--- CBWIRE JS --->
        #wireScripts()#
    </body>
</html>
</cfoutput>
```

{% hint style="warning" %}
CBWIRE will not work if you do not add the wireStyles() and wireScripts() references to your layout or enable autoInjectAssets.
{% endhint %}

## Next Steps

You are ready to go. Now head to the [Making Components](/3.x/essentials/components) section to learn how to create and use CBWIRE components.

We also have numerous [Examples](/3.x/examples) you can review to get up and running quickly.


# Configuration

Change the internal behavior of CBWIRE as needed.

## ColdBox.cfc

You can alter any default behavior by overriding settings in your **config/ColdBox.cfc** file.

```javascript
// File: ./config/ColdBox.cfc
component{
    function configure() {
        moduleSettings = {
            cbwire = {
                "autoInjectAssets": false,
                "cacheSingleFileComponents": false,
                "enableTurbo": false,
                "maxUploadSeconds": 5 * 60, // 5 minutes
                "throwOnMissingSetterMethod" : false,
                "trimStringValues": false,
                "wiresLocation": "wires"
            }
        };
     }
}

```

{% hint style="info" %}
Overriding the module settings is optional.
{% endhint %}

### autoInjectAssets

Set as true to automatically include CBWIRE's CSS and JavaScript assets. This removes the need to manually add references to wireStyles() in your \<head> and wireScripts() at the end of \</body> in your ColdBox layout file. In the next major release, this will default to true. **Defaults to false.**

### cacheSingleFileComponents

Set as true to enable caching of single-file components, meaning Components that are placed in a single .cfm file instead of separating them into a .cfc and .cfm files. CBWIRE requires additional processing to render single-file components. Enabling this setting will increase rendering performance. When enabled, you will need to reinit ColdBox when making changes to the component. We recommend enabling this in production but leaving it set to false when developing your app. **Defaults to false**.

### enableTurbo

Set as true to enable [Turbo](/3.x/integrations/spas-with-turbo), which causes any clicked links or form submissions to be performed in the background via AJAX and updates the DOM without reloading the page. Great when developing single-page applications. **Defaults to false.**

### maxUploadSeconds

The maximum amount of time allowed for uploads to complete.

### throwOnMissingSetter

Set as true to throw a WireSetterNotFound exception if the incoming wire request tries to update a property without a setter on our component. Otherwise, missing setters are ignored. **Defaults to false**.

### trimStringValues

When set to true, any data properties that contain strings will be automatically trimmed. Great for form inputs. **Defaults to false**.

### wiresLocation

The relative folder path where components are stored. **Defaults to 'wires'**.


# How It Works

HTML-over-the-wire explained.

This diagram references the Counter we created in the [Introduction](/3.x) and shows how CBWIRE achieves reactive UI components with zero page refreshing.

<figure><img src="https://1609386017-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEWvXvmxEDxwnAJzKYkxz%2Fuploads%2FDAeDliZCaNuWea21d52O%2FCleanShot%202023-05-22%20at%2006.51.41.png?alt=media&amp;token=6faab4ec-9f5e-4b70-a725-e9c4b9b141ef" alt=""><figcaption></figcaption></figure>

1. The user requests a page from the server that includes our Counter component.
2. ColdBox receives the request.
3. CBWIRE parses our component and initially renders it with its default values.&#x20;
4. The rendered component is sent to the browser.\
   ***It's important to understand that nothing extraordinary has happened at this point. We've returned HTML to the browser from an incoming request. Next is when things get interesting.***
5. The user clicks the button.
6. CBWIRE intercepts the user's click client-side and sends an XHR request to the server.
7. CBWIRE runs the increment() method, updating the data properties.
8. CBWIRE re-renders the template.
9. CBWIRE returns the re-rendered template to the browser.
10. CBWIRE uses Livewire's DOM diffing technology to update the component on the page.


# Release History

Notes on each release.

In this section, you will find the release notes for each version we release under this major version. If you are looking for the release notes of previous major versions use the version switcher at the top left of this documentation book.&#x20;


# What's New With 3.2

## Enhancements

* [CBWIRE 140](https://github.com/coldbox-modules/cbwire/issues/140): Automatically populate data properties with passed parameters when onMount() isn't defined\
  Contributed by Michael Rigsby
* [CBWIRE 139](https://github.com/coldbox-modules/cbwire/issues/139): Add support for calling wire( "MyComponent\@module" ).\
  Contributed by Michael Rigsby
* [CBWIRE 138](https://github.com/coldbox-modules/cbwire/issues/138): Add ability to dispatch browser events
* [CBWIRE 135](https://github.com/coldbox-modules/cbwire/issues/135): Add ability to call event.method() calls from CBWIRE templates

## Bug Fixes

None


# What's New With 3.1

## 09/25/2023

### Enhancements

* [CBWIRE 81](https://github.com/coldbox-modules/cbwire/issues/81): Add configuration property to include CBWIRE styling and JavaScript assets automatically. Remove the need to add wireScripts() and wireStyles() to templateBugs
* [CBWIRE 116](https://github.com/coldbox-modules/cbwire/issues/116): Add onUpdate() and onUpdateProperty() lifecycle hooks
* [CBWIRE 117](https://github.com/coldbox-modules/cbwire/issues/117): Add the ability to refresh all child components from the parent component when an action is called
* [CBWIRE 118](https://github.com/coldbox-modules/cbwire/issues/118): Add the ability to call CBWIRE UDFs from the cbwire template as computed properties are too limiting.
* [CBWIRE 119](https://github.com/coldbox-modules/cbwire/issues/119): Single file components file names are not unique and could create conflicts in high-traffic applications
* [CBWIRE 120](https://github.com/coldbox-modules/cbwire/issues/120): Clear any compiled single file components on ColdBox fwreinit
* [CBWIRE 121](https://github.com/coldbox-modules/cbwire/issues/121): Add params arguments as a substitute for parameters argument when calling onMount
* [CBWIRE 123](https://github.com/coldbox-modules/cbwire/issues/123): Add 'cacheSingleFileComponents' setting to control if single file components are cached
* [CBWIRE 126](https://github.com/coldbox-modules/cbwire/issues/126): Cleanup unnecessary variables available to templates to avoid potential collisions
* [CBWIRE 127](https://github.com/coldbox-modules/cbwire/issues/127): Add the ability to call application helpers defined in ColdBox.cfc or any installed modules from CBWIRE templates.
* [CBWIRE 129](https://github.com/coldbox-modules/cbwire/issues/129): Add resetExcept()

### Bug Fixes

* [CBWIRE 124](https://github.com/coldbox-modules/cbwire/issues/124): Fix child components not re-rendering properly on subsequent requests
* [CBWIRE 122](https://github.com/coldbox-modules/cbwire/issues/122): HTML comments in component templates cause re-renders not to work.


# What's New With 3.0

## 05/18/2023

### Enhancements

[CBWIRE-104](https://github.com/coldbox-modules/cbwire/issues/104): Add Inline Components ( NEW SYNTAX )

[CBWIRE-109](https://github.com/coldbox-modules/cbwire/issues/109): Make components module-aware and allow components to be created within modules

### Changed

[CBWIRE-93](https://github.com/coldbox-modules/cbwire/issues/93): Remove cbValidation as a dependency of CBWIRE

[CBWIRE-103](https://github.com/coldbox-modules/cbwire/issues/103): Increase component rendering performance by bypassing unnecessary ColdBox view caching and lookups

[CBWIRE-105](https://github.com/coldbox-modules/cbwire/issues/105): Refactor core engine for better performance and easier maintenance

[CBWIRE-106](https://github.com/coldbox-modules/cbwire/issues/106):  Remove computedPropertiesProxy as it's no longer needed

[CBWIRE-107](https://github.com/coldbox-modules/cbwire/issues/107): Replace calling computed properties in templates using #args.computed.\[property]\()# with #property()# instead.

[CBWIRE-108](https://github.com/coldbox-modules/cbwire/issues/108): Replace calling data properties in templates using #args.\[property]\()# with #property# instead.

[CBWIRE-110](https://github.com/coldbox-modules/cbwire/issues/110): Using new component format, validation references this.constraints. Change to just 'constraints'.&#x20;

[CBWIRE-113](https://github.com/coldbox-modules/cbwire/issues/113): Change incorrect emitTo( event, component ) signature to instead by emitTo( component, event )

### Bug Fixes

[CBWIRE-97](https://github.com/coldbox-modules/cbwire/issues/97): Empty string and null values are not being properly passed to Livewire

[CBWIRE-100](https://github.com/coldbox-modules/cbwire/issues/100): Fix ability to locate Wires using full path such as appMapping.wires.SomeComponent

[CBWIRE-102](https://github.com/coldbox-modules/cbwire/issues/102): Component actions that update data properties don't always update the DOM

[CBWIRE-111](https://github.com/coldbox-modules/cbwire/issues/111): Calling .see() and .dontSee() in component tests doesn't return the test object for additional method chaining

[CBWIRE-112](https://github.com/coldbox-modules/cbwire/issues/112): Overriding computed properties not working when writing component tests


# What's New With 2.2

## 01/09/2022

### Enhancements

[CBWIRE-99](https://ortussolutions.atlassian.net/browse/CBWIRE-99): Implement lifecycle hook onHydrate().

[CBWIRE-100](https://ortussolutions.atlassian.net/browse/CBWIRE-100): Implement lifecycle hook onHydrate\[Property]\().

[CBWIRE-103](https://ortussolutions.atlassian.net/browse/CBWIRE-103): Implement an automatic trim() for all data properties.

[CBWIRE-124](https://ortussolutions.atlassian.net/browse/CBWIRE-124): Implement the ability to interact with CBWIRE component from JavaScript using cbwire.find( '#args.\_id#' ).

[CBWIRE-125](https://ortussolutions.atlassian.net/browse/CBWIRE-125): Add configuration setting 'enableTurbo' to automatically include everything needed to work with Turbo for single page applications.

[CBWIRE-130](https://ortussolutions.atlassian.net/browse/CBWIRE-130): Add ability to call reset() without passing a key to reset all data properties to their original values.

### Changed

[CBWIRE-93](https://ortussolutions.atlassian.net/browse/CBWIRE-93): Implement onMount() method instead of mount().

### Bug Fixes

[CBWIRE-121](https://ortussolutions.atlassian.net/browse/CBWIRE-121): DocBox generated docs are failing because of file structure.

[CBWIRE-126](https://ortussolutions.atlassian.net/browse/CBWIRE-126): Listeners are being fired immediately when calling emit() when the listener is defined on the same component, which they shouldn't.

[CBWIRE-127](https://ortussolutions.atlassian.net/browse/CBWIRE-127): onHydrate() is firing after actions are performed.

[CBWIRE-129](https://ortussolutions.atlassian.net/browse/CBWIRE-129): Computed properties are not being rendered before actions are called.


# What's New With 2.1

## 11/26/2022

### Enhancements

[CBWIRE-111](https://ortussolutions.atlassian.net/browse/CBWIRE-111) Ability to output component template direct from onRender() method instead of defining a .cfm template in wire/views.

### Bug Fixes

[CBWIRE-119](https://ortussolutions.atlassian.net/browse/CBWIRE-119) Computed properties that do not return a value result in the error 'variable \[VALUE] doesn't exist

[CBWIRE-118](https://ortussolutions.atlassian.net/browse/CBWIRE-118) Nested components are causing the template rendering only to render the last nested template

[CBWIRE-117](https://ortussolutions.atlassian.net/browse/CBWIRE-117) Struct values are not being passed to the template and are instead being replaced with an empty string

[CBWIRE-116](https://ortussolutions.atlassian.net/browse/CBWIRE-116) CBWIRE doesn't work when the ColdBox app is in a subdirectory

[CBWIRE-115](https://ortussolutions.atlassian.net/browse/CBWIRE-115) Getting errors when rendering component templates in the latest version of ColdBox

[CBWIRE-96](https://ortussolutions.atlassian.net/browse/CBWIRE-96) Nested components are not rendering


# What's New With 2.0

## 08/30/2022

### Enhancements

CBWIRE-24: File Uploads

CBWIRE-55: Ability to write unit tests for components

CBWIRE-59: Ability to override the default 'wires' folder location

CBWIRE-60: noRender() method to prevent template rendering during actions

CBWIRE-61: Implement dirty property tracking

CBWIRE-65: Invoke computed properties during template rendering and only execute once per request

CBWIRE-70: Ability to specify a 'moduleRootURI' setting to change the URI path for cbwire

CBWIRE-71: Upgrade Livewire JS to v2.10.6

CBWIRE-81: Option to specify the component's template path using this.template instead of defining renderIt() method.

CBWIRE-82: Disable browser caching on XHR responses

CBWIRE-83: Reduce payload bloat by removing unnecessary data in XHR requests and responses

CBWIRE-84: Move internal methods to a separate Engine object to avoid collisions with user-defined methods

CBWIRE-85: Reject incoming XHR request if 'X-Livewire' HTTP Header is not present

CBWIRE-86: Specify null values for data properties

CBWIRE-87: Dependency injection capabilities to cbwire components

CBWIRE-90: Update to match Livewire's current incoming and outgoing HTTP responses

CBWIRE-91: Ability to use Turbo to create Single-page Applications ( SPAs )

### Bug Fixes

CBWIRE-73: Calling reset( "someProperty" ) throws error

CBWIRE-74: Browser back history doesn't work

CBWIRE-80: On subsequent renderings of components, it's changing the unique id and causing DOM diff issues

CBWIRE-88: Livewire expects params to be an array

CBWIRE-89: Not passing parameters when calling update methods


# Examples

Code snippets to inspire and get you started.

| Name                                                   | Description                                                             |
| ------------------------------------------------------ | ----------------------------------------------------------------------- |
| [Contact Form](/3.x/examples/contact-form)             | A simple contact form component that uses CBWIRE's validation features. |
| [File Upload](/3.x/examples/file-upload)               | Uploading a file                                                        |
| [Multi-select Input](/3.x/examples/multi-select-input) | Binding a multi-select dropdown with a data property                    |

## Examples Repo

In addition to the examples above, we have a GitHub repo that contains more examples of CBWIRE. Each example includes both the code to generate the example and a section where you can see the results in real-time.

<https://github.com/grantcopley/cbwire-examples>

<figure><img src="https://1609386017-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEWvXvmxEDxwnAJzKYkxz%2Fuploads%2FRWScoZ9FxwNOeiOCgu8k%2Fimage.png?alt=media&amp;token=46e5f4eb-212b-4e97-ae82-d4e1f1882f5a" alt=""><figcaption><p>Homepage listing various CBWIRE examples</p></figcaption></figure>

<figure><img src="https://1609386017-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEWvXvmxEDxwnAJzKYkxz%2Fuploads%2FSfkQuyw3qxRZxmkelI1K%2Fimage.png?alt=media&amp;token=73a3ef76-0322-44b2-b9e1-598e3959c377" alt=""><figcaption><p>Individual page showing form validation in CBWIRE</p></figcaption></figure>


# Contact Form

Below is an example of a simple contact form with name, email, phone, and message fields. The fields use CBWIRE's built-in [Validation](/3.x/wire-features/validation) features.

For the validations to work, you must have *cbValidation* installed. You can install it using CommandBox like so:

```
box install cbvalidation
```

## wires/contactForm.cfm

```html
<cfscript>
    // Constraints
    constraints = {
        "name": {
            "required": true
        },
        "email": {
            "required": true,
            "type": "email"
        },
        "phone": {
            "required": true,
            "type": "telephone"
        },
        "message": {
            "required": true,
            "size": "10..500"
        }
    };

    // Data Properties
    data = {
        "name": "",
        "email": "",
        "phone": "",
        "message": "",
        "success": false
    };

    // Actions
    function submitForm() {
        data.success = true;
    }
</cfscript>

<!--- Template --->
<cfoutput>
    <form wire:submit.prevent="submitForm" id="contactForm">
        <div class="form-floating">
            <input wire:model.lazy="name" class="form-control" id="name" type="text" placeholder="Enter your name..." data-sb-validations="required" />
            <label for="name">Name</label>
            <cfif validation.hasErrors( "name" )>
                <div class="text-danger">
                    #validation.getAllErrors( "name" ).first()#
                </div>
            </cfif>
        </div>
        <div class="form-floating">
            <input wire:model.lazy="email" class="form-control" id="email" type="email" placeholder="Enter your email..." data-sb-validations="required,email" />
            <label for="email">Email address</label>
            <cfif validation.hasErrors( "email" )>
                <div class="text-danger">
                    #validation.getAllErrors( "email" ).first()#
                </div>
            </cfif>
        </div>
        <div class="form-floating">
            <input wire:model.lazy="phone" class="form-control" id="phone" type="tel" placeholder="Enter your phone number..." data-sb-validations="required" />
            <label for="phone">Phone Number</label>
            <cfif validation.hasErrors( "phone" )>
                <div class="text-danger">
                    #validation.getAllErrors( "phone" ).first()#
                </div>
            </cfif>
        </div>
        <div class="form-floating">
            <textarea wire:model.lazy="message" class="form-control" id="message" placeholder="Enter your message here..." style="height: 12rem" data-sb-validations="required"></textarea>
            <label for="message">Message</label>
            <cfif validation.hasErrors( "message" )>
                <div class="text-danger">
                    #validation.getAllErrors( "message" ).first()#
                </div>
            </cfif>
        </div>
        <br />
        <!-- Submit success message-->
        <cfif success>
            <div id="submitSuccessMessage">
                <div class="text-center mb-3">
                    <div class="fw-bolder">Form submission successful!</div>
                </div>
            </div>
        </cfif>
        <!-- Submit Button-->
        <button
            class="btn btn-primary text-uppercase <cfif validation.hasErrors()>disabled</cfif>"
            id="submitButton"
            type="submit">Send</button>
    </form>
</cfoutput>
```


# Multi-select Input

```html
<cfscript>
    data = {
        "heroes": []
    };
</cfscript>

<cfoutput>
    <div>
        <label>
            <select wire:model="heroes" multiple>
                <option value="Batman">Batman</option>
                <option value="Superman">Superman</option>
                <option value="Iron Man">Iron Man</option>
            </select>
        </label>

        <cfif arrayLen( heroes )>
            <div class="mt-4 alert alert-primary">You selected <span class="fw-bold">#arrayToList( heroes )#</span>.</div>
        <cfelse>
            <div class="mt-4 alert alert-danger">Select a hero please.</div>
        </cfif>
    </div>
</cfoutput>
```


# File Upload

This example uses CBWIRE's [File Upload](/3.x/wire-features/file-uploads) features.

```html
<cfscript>
    data = {
        "myFile": ""
    };

    function save() {
        // s3.put( data.myFile.get() );
        if ( isObject( data.myFile ) ) {
            data.myFile.destroy();
        }
    }
</cfscript>

<cfoutput>
    <div>
        <form wire:submit.prevent="save">
            <input wire:model="myFile" type="file">
            <div>
                <button type="submit" class="btn btn-primary mt-4">Save</button>
            </div>
        </form>
        <div>
            <div wire:loading wire:target="myFile">Uploading...</div>
        </div>
        <div>
            <cfif isObject( myFile )>
                <cfif myFile.isImage()>
                    <img src="#myFile.getPreviewURL()#" style="width: 300px; height: auto;">
                <cfelse>
                    <div>The file you uploaded is not an image. Preview not available.</div>
                </cfif>
            </cfif>
        </div>
    </div>
</cfoutput>
```


# Resources

Examples, webinars, screencasts, and more.

* CFCasts Mastering CBWIRE 3: <https://cfcasts.com/series/mastering-cbwire-3>
* CBWIRE Examples: <https://github.com/grantcopley/cbwire-examples>
* Demo - DataTable: <https://github.com/grantcopley/cbwire-datatable-example>
* Demo - Task List: <https://github.com/grantcopley/cbwire-task-list-demo>
* Demo - Form Validation: <https://github.com/grantcopley/cbwire-signup-form-demo>
* Up and Running Screencast: <https://cfcasts.com/series/ortus-single-video-series/videos/up-and-running-with-cbwire>
* Into The Box 2021 Presentation: <https://cfcasts.com/series/into-the-box-2021/videos/cbwire-coldbox-+-livewire-grant-copley>
* Ortus Webinar 2022: <https://cfcasts.com/series/ortus-webinars-2022/videos/grant-copley-on-cbwire-+-alpine_js>
* ForgeBox: <https://forgebox.io/view/cbwire>
* GitHub Repository: <https://github.com/coldbox-modules/cbwire>
* API Docs: <https://apidocs.ortussolutions.com/#/coldbox-modules/cbwire/>
* Issue Tracker: <https://github.com/coldbox-modules/cbwire/issues>


# Components

Sections or areas of your app that are reactive to user input.

Components are sections or areas of your site that you want to be reactive to user input. **They can be as big or small as you like**. For example, you may have a Signup form component that covers multiple steps or a button component that you reuse throughout your app.

Components are generally made up of [Data Properties](/3.x/essentials/properties), [Computed Properties](/3.x/essentials/computed-properties), [Actions](/3.x/essentials/actions), and an HTML template.&#x20;

```html
<cfscript>
    // Data properties
    data = {
        "property1": "defaultValue",
        "property2": "defaultValue"
    };
    
    // Computed properties
    computed = {
        "computedProperty" : function() {
            // return something
        }    
    };
    
    // Actions
    function action1() {
        data.property1 = "another value";
    }
</cfscript>

<!-- HTML Template -->
<cfoutput>
    <div>
        <h1>My Component</h1>
    </div>
</cfoutput>
```

{% hint style="info" %}
Increase the performance of component rendering in your production environments with the 'cacheSingleFileComponents' [configuration](/3.x/configuration) setting.
{% endhint %}

{% hint style="info" %}
**Your template must have a single outer element for CBWIRE to bind to.** Our example above uses a **\<div>** element but can use any outer element. Adding more than one outer element will lead to DOM diffing issues and unexpected behavior.
{% endhint %}

{% hint style="info" %}
By default, components should be placed in a **./wires** folder in the project root.
{% endhint %}

{% hint style="success" %}
Within your templates, you can access your [Data Properties](/3.x/essentials/properties), [Computed Properties](/3.x/essentials/computed-properties), and [Actions](/3.x/essentials/actions), and utilize any of the powerful template features listed under Template Features in the left-hand menu. Details on how to use these
{% endhint %}

## Separating Component Definition and Template

You can place the above code in separate files to separate your component and template definitions. **CFC components must extend 'cbwire.models.Component'**.

**./wires/MyComponent.cfc**

```javascript
component extends="cbwire.models.Component" {
    // Data properties
    data = {
        "property1": "defaultValue",
        "property2": "defaultValue"
    };
    
    // Computed properties
    computed = {
        "computedProperty" : function() {
            // return something
        }    
    };
    
    // Actions
    function action1() {
        data.property1 = "another value";
    }
}
```

**./wires/MyComponent.cfm**

```html
<!--- Template --->
<cfoutput>
    <div>
        <h1>My Component</h1>
    </div>
</cfoutput>
```

{% hint style="info" %}
Separating your template and component is how previous versions of CBWIRE worked. We recommend using the less verbose option of including both definitions in a single .CFM file for smaller UI components, and creating separate files for more complex UI components.
{% endhint %}

## Rendering Components

You can render a CBWIRE component using the **wire()** method.&#x20;

```html
<!--- ./layouts/Main.cfm --->
<body>
    <div>
        #wire( "ShowPosts" )#
    </div>
</body>
```

```html
<!--- ./views/posts/index.cfm --->
<cfoutput>
    <h1>My Posts</h1>
    #wire( "ShowPosts" )#
</cfoutput>
```

{% hint style="info" %}
You can call **wire()** from within your ColdBox layouts, ColdBox views, and also from your component templates ( nested components ).
{% endhint %}

## External Components

You can render wires from folders and subfolders outside of the default ./wires folder.

```html
<cfoutput>
    <div>
        #wire( "myFolder.MyComponent" )#
        #wire( "myFolder.subFolder.MyComponent" )#
    </div>
</cfoutput>
```

You can also reference components within another ColdBox module by using the @module syntax.

```html
<cfoutput>
    <div>#wire( "MyComponent@myModule" )#</div>
</cfoutput>
```

## Passing Parameters

You can pass data into a component as an additional argument using **wire()**.

```html
<body>
    <div>
        #wire( "ShowPost", { "post": post } )#
    </div>
</body>
```

{% hint style="success" %}
By passing in parameters, you can create reusable UI components that are unique but similar in functionality. For example, you could create a Button component that you use throughout your app.
{% endhint %}

## Using Parameters

Parameters are passed into your component's **onMount()** method. This is an optional method you can add.

```xml
<!--- ./views/posts/index.cfm --->
#wire( "ShowPost", { post: currentPost } )#

<!--- ./wires/ShowPost.cfm --->
<cfscript>
    data = {
        "title": ""
    };

    function onMount( params, event, rc, prc ) {
        data.title = params.post.getTitle();
    }
}
</cfscript>

<cfoutput>
    <div>Title: #title#</div>
</cfoutput>
```

{% hint style="info" %}
CBWIRE only executes **onMount()** once when the component is initially rendered. It is not executed for subsequent XHR requests of the component.
{% endhint %}

## Auto Population of Data Properties

As of CBWIRE 3.2, properties that you pass into your component will be automatically populated if onMount() IS NOT defined and a matching data property is found.&#x20;

{% hint style="info" %}
Passed-in properties must have a data type of string, boolean, numeric, date, array, or struct.
{% endhint %}

```html
<!--- ./views/posts/index.cfm --->
#wire( "ShowPost", { title: "Some title" } )#

<!--- ./wires/ShowPost.cfm --->
<cfscript>
    data = {
        "title": ""
    };
}
</cfscript>

<cfoutput>
    <!--- outputs 'Title: Some title --->
    <div>Title: #title#</div>
</cfoutput>
```


# Templates

The HTML that makes up your components.

Templates are the HTML section of your [Components](/3.x/essentials/components) and consist of any valid CFML tags. This includes \<cfif>, \<cfloop>, etc.

```html
<cfscript>
    // Component stuff goes here
    function doSomething() {}
</cfscript>

<cfoutput>
    <!-- HTML template goes here -->
    <div>
        <button wire:click="doSomething">Click here</button>
        <!-- Any valid CFML here -->
        <cfif datePart( 'h', now() ) lt 12>
            <p>Good morning!</p>
        <cfelse>
            <p>Good afternoon!</p>
        </cfif>
    </div>
</cfoutput>
```

## Outer Element

Your templates must have a single outer element for CBWIRE to properly bind to your component and update the DOM. This can be any valid HTML element. Below we are using a DIV element.

```html
<cfoutput>
    <!-- GOOD: single outer element -->
    <div>
        <p>My awesome component</p>
    </div>
</cfoutput>

<cfoutput>
    <!-- BAD: 2 outer elements -->
    <div>
        My awesome component    
    </div>
    <div>
        <p>This won't work.</p>
    </div>
</cfoutput>
```

## Accessing Properties

You can access your [Data Properties](#data-properties) from your template by calling the property name.

```html
<cfscript>
    data = {
        "greeting": "Hello from CBWIRE"
    };
</cfscript>

<cfoutput>
    <div>
        Greeting: #greeting#
    </div>
</cfoutput>
```

You can access your [Computed Properties](/3.x/essentials/computed-properties) from your template by calling the property name as a method.

```html
<cfscript>
    computed = {
        "greeting": function() { 
            return "Hello from CBWIRE" 
        }
    };
</cfscript>

<cfoutput>
    <div>
        Greeting: #greeting()#
    </div>
</cfoutput>
```

## Helper Methods

You can access any global helper methods you have defined in your ColdBox application, along with any modules you have installed.

For example, if you've installed the cbi8n module ( an internalization module for ColdBox ), you can access its global helper methods in your template, such as the `$r()` method for displaying text in various languages.

```html
<cfoutput>
    <div>
        #$r( "greeting" )#
    </div>
</cfoutput>
```

## Nesting Components

You can nest components as much as you need by simply calling **wire()** from within a component's template.

```html
<!--- ./wires/ShowPosts.cfm --->
<cfscript>
    // Data properties, actions go here.
</cfscript>

<cfoutput>
    <div>
        <h1>Posts</h1>
        #wire( "AddPostForm" )#
        ...
    </div>
</cfoutput>
```

You can also conditionally render nested components.

```html
<cfscript>
    data = {
        "showForm" : false
    };
</cfscript>

<cfoutput>
    <div>
        <cfif showForm>
            #wire( "MyForm" )#
        </cfif>    
        <button wire:click="$toggle( 'showForm' )">Toggle form</button>
    </div>
</cfoutput>
```


# Data Properties

The state of the our components.

Components have state known as Data Properties.

Data Properties are defined by creating a **data** structure on your component and assigning each property a default value.

```html
<!--- ./wires/SomeComponent.cfm --->
<cfscript>
    data = {
        "propertyName": "defaultValue"
    };
</cfscript>
```

{% hint style="info" %}
**Property names must be surrounded by single or double quotes.**

JavaScript is a case-sensitive language and CFML isn't. To preserve the casing of your property names, you must surround them with quotes.

```
// Bad
data = {
    propertyName: "defaultValue"
};

// Good
data = {
    "propertyName": "defaultValue"
};
```

{% endhint %}

{% hint style="info" %}
Data Properties are parsed by JavaScript and therefore can only store values that are JavaScript friendly: **strings, numeric, arrays, structs, or booleans**.
{% endhint %}

{% hint style="danger" %}
Data Properties are visible to JavaScript. **You SHOULD NOT store sensitive data in them**.
{% endhint %}

## Initial Values

Data properties should be assigned a default value, even if it's just an empty string.

```html
<cfscript>
    data = {
        "success": false,
        "message: "Hello World"
    };
</cfscript>
```

## Using Data Properties

You can access Data Properties from within your component [Actions](/3.x/essentials/actions) like so.

```html
<cfscript>
    // Data properties
    data = {
        "task": ""
    };
    
    // Action
    function addTask(){
        taskService.create( data.task );
        data.task = "";
    }
</cfscript>
```

You can also reference Data Properties within your component template using **#propertyName#***.*

```html
<cfoutput>
    <div>
        <h1>Task</h1>
        <div>#task#</div>
    </div>
</cfoutput>
```

## Resetting Data Properties

You can reset properties back to their original value inside your [Actions](/3.x/essentials/actions) using **reset()**.

<pre class="language-xml"><code class="lang-xml"><strong>&#x3C;cfscript>
</strong><strong>    // Data properties
</strong><strong>    data = {
</strong><strong>        "message" : "Hello world"
</strong><strong>    };
</strong><strong>    
</strong><strong>    // Actions    
</strong><strong>    function resetForm() {
</strong><strong>        reset();
</strong><strong>    }
</strong><strong>&#x3C;/cfscript>
</strong><strong>
</strong><strong>&#x3C;cfoutput>
</strong><strong>    &#x3C;div>
</strong><strong>        &#x3C;button wire:click="resetForm">Reset&#x3C;/button>
</strong><strong>    &#x3C;/div>
</strong><strong>&#x3C;/cfoutput>
</strong></code></pre>

You can reset individual or all Data Properties.

```javascript
function resetForm() {
    reset( "message" ); // resets 'message' data property
    reset( [ "message", "anotherprop" ] ); // reset multiple properties at once
    reset(); // resets all properties
}
```

You also can reset all properties EXCEPT the properties you pass.

```javascript
function resetForm() {
    resetExecept( "email" );
    resetExcept( [ "email", "phoneNumber" ] );
}
```

## Data Binding

You can bind your data properties and HTML elements using **wire:model**.

```html
<cfscript>
    // Data properties
    data = {
        "message" : "",
        "isChecked": false,
        "isSelected": "",
        "hero": ""
    };
</cfscript>

<cfoutput>
    <div>
        <form>
            <input wire:model="message" type="text">
            <input wire:model="isChecked" type="checkbox" value="true">
            <input wire:model="isSelected" name="isSelected" type="radio" value="true">
            <input wire:model="isSelected" name="isSelected" type="radio" value="false">
            <select wire:model="hero">
               <option value=""></option>
                <option value="Batman">Batman</option>
                <option value="Superman">Superman</option>
            </select>
        </form>
    </div>
</cfoutput>
```

There are also several [modifiers](/3.x/template-features/directives) you can add to control when and how requests are sent to your server.


# Computed Properties

Dynamic, cached, properties that can return any CFML data type.

Computed Properties are dynamic properties and are helpful for deriving values from a database or another persistent store like a cache.&#x20;

Computed Properties are similar to [Data Properties](/3.x/essentials/properties) with some key differences:

* They are declared as inline functions using **computed***.*
* They can return any CFML data type, not just values that can be parsed by JavaScript like [Data Properties](/3.x/essentials/properties).

## Defining Properties

You can define Computed Properties on your components using **computed**.&#x20;

```html
<cfscript>
    computed = {
        "tasks": function() {
            return queryExecute( "
                select *
                from tasks
            " );
        }
    };
</cfscript>
```

## Accessing Properties

You can access Computed Properties in your component template using **propertyName()**.

```html
<cfscript>
    computed = {
        "currentTime": function() {
            return now();
        }
    };
</cfscript>

<cfoutput>
    <div>
        Current time: #currentTime()#
    </div>
</cfoutput>
```

You can also access Computed Properties from within your [Actions](#actions).

```html
<cfscript>
    computed = {
        "currentTime" : function() {
            return now();
        }
    };    
    
    function sendEmail() {
        if ( dateDiff( "d", computed.currentTime() ) > 3 ) {

        }
    }
</cfscript>
```

{% hint style="info" %}
Computed Properties are defined as a CFML closure. That means that to get the result from the function, you must invoke it like so.

```javascript
myComputedProperty() // good
```

```
myComputedProperty // bad
```

{% endhint %}

## Caching

**Computed Properties are cached for the lifetime of the request.** If you reference your Computed Property three times in your component template or from within a component action, it will only execute once.

```html
<cfscript>
    computed = {
        "getUUID": function() {
            return createUUID();
        }
    }
</cfscript>

<cfoutput>
    <div>
        <p>#getUUID()#</p>
        <p>#getUUID()#</p> <!-- Outputs the same ID because of caching -->
    </div>
</cfoutput>
```

You can prevent caching on a computed property by passing a false argument when invoking it.

```html
<p>#getUUID()#</p>
<p>#getUUID( false )#</p> <!-- Does not use caching --->
```


# Actions

Methods that are invoked based on user interactions.

Actions are methods on your component that either change the component's state ( Data Properties ) or perform some action needed ( such as updating your database ).

Here is a basic example of how to use it:

```html
<cfscript>
    data = {
        "currentTime" : now()
    };
    
    function updateTime() {
        data.currentTime = now();
    }
</cfscript>

<cfoutput>
    <p>
        Current time: #currentTime#
    </p>
    <button wire:click="updateTime">Update</button>
</cfoutput>
```

{% hint style="info" %}
Actions do not need to return any value. Return values are ignored.
{% endhint %}

## Running Actions

CBWIRE listens for browser events and invokes actions using [Directives](/3.x/template-features/directives). The directives follow the format: **wire:\[browser event]=\[action]**.

Some examples of events you can listen for include:

| Event   | Directive    |
| ------- | ------------ |
| click   | wire:click   |
| keydown | wire:keydown |
| submit  | wire:submit  |

Here are a few examples of each in HTML:

```html
<button wire:click="doSomething">Do Something</button>

<input wire:keydown.enter="doSomething">

<form wire:submit.prevent="save">
    <button>Save</button>
</form>
```

You can listen for any browser events on elements by using the **wire:\[event]** directive, where \[event] is the event's name. For example, to listen for a "foo" event on a button element, you would use the following code:&#x20;

```html
<button wire:foo="someAction">
```

On some elements such as forms or links, you need to add a **.prevent** modifier to prevent the browser's default behavior. Otherwise, the browser will cause a page reload and you will get unintended results.

```html
<a href="" wire:click.prevent="doSomething">Do Something</a>
```

## Passing Parameters

You can pass parameters to your actions, such as here using **actionName( params )**.

```html
<cfoutput>
    <div>
        <button wire:click="addTask('Some Task')">Add Task</button>
    </div>
</cfoutput>
```

The parameter is then passed through to your [Actions](/3.x/essentials/actions) via function arguments.

```javascript
// Action
function addTask( taskName ){
    queryExecute( "
        insert into tasks (
            name
        ) values (
            :name
        )
    ", { name = arguments.taskName } );
}
```

## Magic Actions

There are a few magic actions already available to your components.

| Action                        | Description                                            |
| ----------------------------- | ------------------------------------------------------ |
| $refresh                      | Will re-render the component without firing any action |
| $set( 'dataproperty', value ) | Shortcut to update the value of a property             |
| $toggle( 'dataproperty' )     | Shortcut to toggle boolean properties off and on       |

Consider the example below.

```html
<cfscript>
    data = {
        "message": ""
    };
    
    function setMessageToHello() {
        data.message = "Hello";
    }
</cfscript>

<div>
    #message#
    <button wire:click="$set( 'message', 'Hello' )">Say Hi</button>
</div>
```

## Refresh

Sometimes you may need to force your component to completely refresh in the DOM. This is particularly true when you have nested components.

```html
<cfoutput>
    <div>
        <cfif showTeamForm>
            #wire( "TeamForm" )#
        <cfelse>
            <button wire:click="selectTeamForm">Show Team Form</button>
            #wire( "UserForm" )#
        </cfif>
    </div>
</cfoutput>
```

To force a refresh, simply call **refresh()** from any action on your component.

```javascript
<cfscript>
    data = {
        "showTeamForm": false
    };

    function selectTeamForm() {
        data.showTeamForm = true;      
        refresh(); // force a refresh
    }
</cfscript>
```


# Events

A simple way for UI components to communicate with each other.

Events and listeners provide an elegant means for your components to communicate with each other. You can emit events from one component, listen for them on another component, and then execute code and re-render the listener.

## Emitting Events

You can fire events from:

* Actions using **emit(), emitUp(), emitSelf(),** and **emitTo()**
* Templates using **$emit()**
* [JavaScript](/3.x/essentials/javascript) using **cbwire.emit()**

```html
<!--- Action --->
<cfscript>
    function addPost() {
        emit( "postAdded" );
    }
</cfscript>
```

```html
<!--- Templates --->
<cfoutput>
    <div>
        <button wire:click="$emit( 'postAdded' )">Add Post</button>
    </div>
</cfoutput>

```

```html
<!--- Javascript --->
<script>
    cbwire.emit( 'postAdded' );
</script>
```

## Passing Parameters

You can send parameters as your emitting an event.

```javascript
function addPost() {
    var post = getInstance( "PostService" ).create( data );
    emit( "postAdded", post.getId() );
}

<button wire:click="$emit( 'postAdded', post.getId() )">Add Post</button>

<script>
    cbwire.emit( 'postAdded', [ '#post.getID()#' ] );
</script>
```

## Scoping Events

### emitUp

When working with nested components, sometimes you may want to emit events only to parent components and no children or sibling components.

For this, you can use the **emitUp()** method.

```html
<cfoutput>
    <div>...</div>
</cfoutput>

<cfscript>
    function addPost() {
        emitUp( "postAdded" );
    }
</cfscript>
```

```html
<button wire:click="$emitUp( 'postAdded' )">Add Post</button>
```

### emitTo

You can emit events to components of a specific type ( name ) using **emitTo()**.

```html
<cfoutput>
    <div>...</div>
</cfoutput>

<cfscript>
    function addPost() {
        emitTo( "topBar", "postAdded" );
    }
</cfscript>
```

```html
<button wire:click="$emitTo( 'topBar', 'postAdded' )">Add Post</button>
```

### emitSelf

You can emit events to the component that fired the event using **emitSelf()**.

```html
<cfoutput>
    <div>...</div>
</cfoutput>

<cfscript>
    function addPost() {
        emitSelf( "postAdded" );
    }
</cfscript>
```

```html
<button wire:click="$emitSelf( 'postAdded' )">Add Post</button>
```

## Listeners

You register event listeners using the **listeners** struct of your component.

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

```html
<cfscript>
    listeners = {
        "postAdded": "incrementPostCount" 
    };
    
    function incrementPostCount() {
        // Increment the post count
    }
</cfscript>
```

{% hint style="info" %}
JavaScript keys are case-sensitive. You can preserve the key casing in CFML by surrounding your listener names in quotations.
{% endhint %}

## Dispatching Browser Events

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

```html
// 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>

```

You can listen for the event using vanilla JavaScript:

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

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

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


# Lifecycle Methods

Various component lifecycle events you can leverage for your needs.

CBWIRE provides various lifecycle methods you can hook into to update and render your components.

## Order of Operations

The lifecycle methods are executed in the following order **when a component is initially loaded**:

1. onMount()
2. Render component

**For subsequent AJAX requests**, lifecycle methods are executed in this order.

1. onHydrate\[DataProperty]\()
2. onHydrate()
3. onUpdate\[DataProperty]\()
4. onUpdate()
5. Execute actions
6. Render component

## onMount

Runs only once when a component is initially wired. This can be used to inject data values into your component either via params you pass in when calling wire(), or pulling in values from the RC or PRC scopes.

```javascript
<cfscript>
    function onMount( event, rc, prc, params ){
        data.someProperty = rc.someValue;
        data.anotherProperty = params.passedInParam;
    }
</cfscript>
```

{% hint style="warning" %}
onMount() only fires when the component is initially rendered and does not fire on subsequent requests when your component re-renders. This can cause issues when referencing things such as the RC or PRC scope. If you are passing in values with the RC or PRC scope, you will need to store the values as data properties to ensure they are available to your component in subsequent requests.
{% endhint %}

## onHydrate

Runs on subsequent requests after a component is hydrated, but before computed properties are rendered, before a property is updated or action is performed, or before the component is rendered.

```javascript
<cfscript>
    function onHydrate( data ) {
        // Note that computed properties are not rendered yet
        data.hydrated = true;
    }
</cfscript>
```

## onHydrate\[ Property ]

Runs on subsequent requests, after a specific data property is hydrated, but before computed properties are rendered, before an action is performed, or before the component is rendered.

```javascript
<cfscript>
    data = {
        "count": 1
    };

    function onHydrateCount( data ) {
        // Note that computed properties are not rendered yet
        data.count += 1;
    }  
</cfscript>
```

## onUpdate\[ Property ]

Runs on subsequent requests, after a data property is updated using wire:model or $set. Only runs when the targeted data property is updated.

<pre class="language-javascript"><code class="lang-javascript"><strong>&#x3C;cfscript>
</strong>    data = {
        "count": 1
    };
    
    function onUpdateCount( newValue, oldValue ) {
        if ( newValue >= 100 ) {
            // Reset back to 1
            data.count = 1;
        }

    }
&#x3C;/cfscript>
</code></pre>

## onUpdate

Runs on subsequent requests, after any data property is updated using wire:model or $set.

{% hint style="info" %}
onUpdate() will only fire if the incoming request is updating a single data property, such as when using wire:model.&#x20;
{% endhint %}

```javascript
<cfscript>
    function onUpdate( newValues, oldValues ) {
        // ....
    }
</cfscript>
```

## onRender

Runs during the rendering of a component. If *onRender()* is defined, CBWIRE will use what is returned as the component's template. Otherwise, it will render the component normally.&#x20;

```javascript
<cfscript>
    data = {
        "rendered": true
    };
    
    computed = {
        "currentDate": function() {
            return now();
        }
    }

    function onRender( args ) {
        return "
            <div>
                <div>Rendered: #args.rendered# at #args.currentDate#</div>
            </div>
        ";
    }
</cfscript>
```


# JavaScript

Call Actions, emit and listen for Events, and more - all from Vanilla JavaScript.

CBWIRE provides a handful of JavaScript hooks and functionality you can use as needed.

## Inline JavaScript

We recommend you use [AlpineJS](/3.x/integrations/alpinejs) for most of your JavaScript needs, but you can use *\<script>* tags directly inside your components.

```html
<div>
    <!--- Your component's template --->
    <script>
        document.addEventListener('livewire:load', function () {
            // Your JS here.
        })
    </script>
</div>
```

{% hint style="info" %}
Your scripts will be run only once upon the first render of the component. If you need to run a JavaScript function later, you can emit the [Event](/3.x/essentials/events) from the component and listen to it in JavaScript.
{% endhint %}

## Lifecycle Hooks

CBWIRE allows you to execute JavaScript during various events.

<table><thead><tr><th width="251">Hook</th><th>Description</th></tr></thead><tbody><tr><td>component.initialized</td><td>Called when a component has been initialized on the page by CBWIRE</td></tr><tr><td>element.initialized</td><td>Called when CBWIRE initializes an individual element</td></tr><tr><td>element.updating</td><td>Called before CBWIRE updates an element during its DOM-diffing cycle after a network roundtrip</td></tr><tr><td>element.updated</td><td>Called after CBWIRE updates an element during its DOM-diffing cycle after a network roundtrip</td></tr><tr><td>element.removed</td><td>Called after CBWIRE removes an element during its DOM-diffing cycle</td></tr><tr><td>message.sent</td><td>Called when a CBWIRE update triggers a message sent to the server via AJAX</td></tr><tr><td>message.failed</td><td>Called if the message send fails for some reason</td></tr><tr><td>message.received</td><td>Called when a message has finished its roundtrip, but before CBWIRE updates the DOM</td></tr><tr><td>message.processed</td><td>Called after CBWIRE processes all side effects (including DOM-diffing) from a message</td></tr></tbody></table>

```html
<cfoutput>
    <div>
        <!-- HTML goes here -->
        <script>
            document.addEventListener("DOMContentLoaded", () => {
                cbwire.hook('component.initialized', (wire) => {})
                cbwire.hook('element.initialized', (el, wire) => {})
                cbwire.hook('element.updating', (fromEl, toEl, wire) => {})
                cbwire.hook('element.updated', (el, wire) => {})
                cbwire.hook('element.removed', (el, wire) => {})
                cbwire.hook('message.sent', (message, wire) => {})
                cbwire.hook('message.failed', (message, wire) => {})
                cbwire.hook('message.received', (message, wire) => {})
                cbwire.hook('message.processed', (message, wire) => {})
            });
        </script>
    </div>
</cfoutput>

<cfscript>
    <!--- Component definition goes here --->
</cfscript>
```

## Component Interaction

You can interact with your component's actions, set data properties, and more, using *cbwire.find*. Once you have a reference to the component, you can use the methods below.

```html
<cfoutput>
    <div>
        <!-- HTML goes here -->
        <script>
            document.addEventListener("livewire:load", function() {
                // _id contains the id of our wire
                var component = cbwire.find('#_id#');
                // gets the value of a data property called 'count'
                var count = component.count;
                // updates the values of a data property
                component.count = 5;
                // calls the increment action on our wire
                component.increment();          
                // calls the addTask action and passes parameters   
                component.addTask( 'someTask' ); 
                // same as increment call above
                component.call( 'increment' ); 
                // On someEvent, console log
                component.on( 'someEvent', function() {
                    console.log('Got someEvent');
                } );
                // emits someEvent and pass parameters
                component.emit('someEvent', 'foo', 'bar');
            } );
        </script>
    </div>
</cfoutput>
```


# Testing

Test your components using TestBox.

CBWIRE includes a beautiful test API to test your front-end components quickly.

## Test Example

{% hint style="info" %}
To start, make sure you extend *BaseWireTest* in your test spec.
{% endhint %}

You can invoke your component by calling **wire()** and then chain additional state changes and assertions.

```javascript
component extends="cbwire.models.BaseWireTest" {

    function run(){

        describe( "TaskList.cfc", function(){
	
	    it( "calling 'clearTasks' removes the tasks", function() {
        
                wire( "TaskList" )
                    // Sets our data properties
                    .data( "tasks", [ "task1" ] )
                    // Verifies output in our template rendering
                    .see( "<li>task 1</li>" )
                    // Runs the 'clearTasks' action
                    .call( "clearTasks" )
                    // Verifies updated template rendering
		    .dontSee( "<li>task 1</li>" );
		} );
	
	} );
    }
}
```

## Test Methods

### data

Set a data property to the specified value.

```javascript
wire( "TaskList" )
    .data( "tasks", [ "task1", "task2" ] ) // one property at a time
    .data( { "tasks" : [ "task1", "task2" ] } ); // struct of properties
```

### computed

Set a computed property to the specified closure.

```javascript
wire( "TaskList" )
    .computed( "count", function() { return 3; } ) // one property at a time
    .computed( { "count" : function() { return 3; } } ); // struct of properties
```

### toggle

Toggles a data property between true and false.

```javascript
wire( "TaskList" ).toggle( "showModal" );
```

### call

Calls an action. An optional array of parameters can be provided.

```javascript
wire( "TaskList" ).call( "clearTasks" );
wire( "TaskList" ).call( "clearTasks", [ param1, param2 ] );
```

### emit

Emits an event and fires any listeners that are defined on the component. An optional array of parameters can be provided, which will be passed on to listeners.

```javascript
wire( "TaskList" ).emit( "addedTask" );
wire( "TaskList" ).emit( "addedTask", [ param1, param2 ] );
```

### see

Verifies a value can be found in the current component rendering. Otherwise, the test fails.

```javascript
wire( "TaskList" ).see( "<h1>My Tasks</h1>" );
```

### dontSee

Verifies a value is not found in the current component rendering. Otherwise, the test fails.

```javascript
wire( "TaskList" ).dontSee( "<h1>Someone Else's Tasks</h1> ");
```

### seeData

Verifies a data property matches a specified value. Otherwise, the test fails.

```javascript
wire( "TaskList" ).seeData( "tasksRemoved", true );
```

### dontSeeData

Verifies a data property does not match a specified value. Otherwise, test fails.

```javascript
wire( "TaskList" ).dontSeeData( "tasksRemoved", true );
```


# Validation

Powerful validations for your forms and input elements.

CBWIRE includes powerful validations provided by [cbValidation](https://coldbox-validation.ortusbooks.com/) that you can use to validate your [Properties](/3.x/essentials/properties).

## Installation

You'll need to install cbValidation to use the validation features with CBWIRE.

To install cbValidation, run the following command in CommandBox:

```
box install cbvalidation
```

{% hint style="info" %}
Previous versions of CBWIRE included cbValidation automatically. However, this introduced issues if you wanted to use a module version different from CBWIRE's version, so you now must manually install cbValidation.
{% endhint %}

## Defining Constraints

You can define constraints within your components by populating a *constraints* struct. Once constraints are defined, CBWIRE will automatically validate your component on each request.

<pre class="language-html"><code class="lang-html">&#x3C;cfscript>
    constraints = {
        "task": { required: true }
    };
    
    // Data Properties
    data = {
        "task": ""
    };
&#x3C;/cfscript>

<strong>&#x3C;cfoutput>
</strong>    &#x3C;div>
        &#x3C;!-- HTML goes here -->
    &#x3C;/div>
&#x3C;/cfoutput>
</code></pre>

## Manual Validation

You can manually validate your component using the *validate()* or *validateOrFail()* methods.

### validate

Returns a *ValidateResult* object.

```html
<cfscript>
    constraints = {
        "task": { required: true }
    };

    // Action
    function addTask() {
        var result = validate(); // ValidateResult object
        
        if ( !result.hasErrors() ) {
            // Do something
        }
    }
</cfscript>

<cfoutput>
    <div>
        <!-- HTML goes here -->
    </div>
</cfoutput>
```

### validateOrFail

Silently fails and prevents further processing of the current action.

```html
<cfscript>
    constraints = {
        "task": { required: true }
    };

    // Action
    function addTask() {
        validateOrFail();
        // Continue if validation passes
    }
</cfscript>

<cfoutput>
    <div>
        <!-- HTML goes here -->
    </div>
</cfoutput>
```

{% hint style="info" %}
With *validateOrFail()*, the error is gracefully caught and any further processing of the invoked action is prevented. The XHR response and re-rendered template are still returned. The actual errors themselves are available to the template using the *validation* variable.

If you need more granular control over the response, use *validate()* instead.
{% endhint %}

## Explicit Constraints

If you can also run validations against any constraints you provide by passing them to the *validate()* method.

```html
<cfscript>
    // Action
    function addTask() {
        var result = validate(
            target=data,
            constraints={
                "task": { required: true }
            }
        ); // ValidateResult object
        
        if ( !result.hasErrors() ) {
            // Do something
        }
    }
</cfscript>

<cfoutput>
    <div>
        <!-- HTML goes here -->
    </div>
</cfoutput>
```

## Displaying Errors

You can access the *ValidationResults* object using the *validation* variable. This includes helpful methods you can use for displaying error messages.

```html
<cfscript>
    // ....
</cfscript>

<cfoutput>
<div>
    <input wire:model="task" type="text">
    <button wire:click="addTask">Add</button>
    
    <cfif validation.hasErrors( "task" )>
        <cfloop array="#validation.getAllErrors( "task" )#" index="error">
            <div>#error#</div>
        </cfloop>
    </cfif>
</div>
</cfoutput>
```


# File Uploads

Provide your users with file uploads and thumbnail previews without page refreshes.

CBWIRE makes uploading and storing files easy.

Here's an example of a simple Wire that handles uploading a photo:

```html
<cfscript>
    data = {
        "photo": ""
    };
    
    function save() {
        // data.photo is now an instance of FileUpload ( see below )
        fileWrite( expandPath( "./somewhere.jpg" ), data.photo.get() );       
        data.photo.destroy();
    }
}
</cfscript>

<cfoutput>
    <form wire:submit.prevent="save">
        File: <input type="file" wire:model="photo">
        <div><button type="submit">Save</button></div>
    </form>
</cfoutput>
```

Handling file inputs is no different than handling any other input type with CBWIRE. Add **wire:model** to the input tag and CBWIRE will take care of the rest.

Several things are happening under the hood to make file uploads work:

1. CBWIRE makes an initial request to the server to get a temporary "signed" upload URL.
2. Once the URL is received, JavaScript then does the actual "upload" to the signed URL, storing the upload in a temporary directory designated by CBWIRE and returning the new temporary file's unique hash ID.
3. Once the file is uploaded, and the unique hash ID is generated, CBWIRE makes a final request to the server, telling it to "set" the desired data property to the upload file as an instance of FileUpload ( see below ).
4. Now the data property (in this case, *photo* ) is set to an instance of *FileUpload\@cbwire* and is ready to be stored or validated at any point.

## FileUpload Object

CBWIRE will automatically upload your files and set your associated data property to an instance of *FileUpload\@cbwire*. Here are some of the methods you can use that are helpful.

| Method                    | Description                                                                                                                                                                          |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| getComp()                 | Returns an instance of your current Wire.                                                                                                                                            |
| getParams()               | Returns any params that are passed in, including the data property name.                                                                                                             |
| get()                     | Returns the contents of the file uploaded.                                                                                                                                           |
| getBase64()               | Returns base64 encoded string of the file.                                                                                                                                           |
| getBase64Src()            | Returns a base64 src string that can be used with \<img tag>. It is recommended to use this carefully because with larger objects, this can slow down CBWIRE response times.         |
| getTemporaryStoragePath() | Returns the temporary storage path where the file is stored by CBWIRE.                                                                                                               |
| getMetaPath()             | Returns the file path to meta information of the uploaded file. You can find additional details here like the name of the file when it was uploaded, the client file extension, etc. |
| getMeta()                 | Returns all captured meta information on the file upload.                                                                                                                            |
| getSize()                 | Returns the size of the file upload.                                                                                                                                                 |
| getMimeType()             | Returns the mime type of the file upload.                                                                                                                                            |
| isImage()                 | Returns true if this is an image.                                                                                                                                                    |
| getPreviewURL()           | Provides a URL to preview the file uploaded. It only works with image uploads.                                                                                                       |
| destroy()                 | Deletes the temporary storage and metadata of the file upload. It's essential to use this after storing the file upload in permanent storage.                                        |

## Loading Indicators

You can display a loading indicator scoped to the file input during upload like so:

```html
<input type="file" wire:model="photo">
 
<div wire:loading wire:target="photo">Uploading...</div>
```

The "Uploading..." message will be shown as the file is uploading and then hidden when the upload is finished.

This works with the entire [Loading States API](/3.x/template-features/loading-states).


# Query String

Set your data properties with incoming query string values.

It can sometimes be helpful to update the browser's query string when your component's state changes.

Let's say we are building a component to search articles.

```html
<!--- ./wires/SearchArticles.cfm --->
<cfscript>
    data = {
        "search": ""
    };
</cfscript>

<cfoutput>
    <div>
        <input wire:model="search" type="search" placeholder="Search articles...">
    </div>
</cfoutput>
```

We can automatically populate the search property above from the URL query string by adding a *queryString* array to our component.

```
queryString = [ "search" ];
```

```html
<!-- ./wires/SearchArticles.cfm -->
<cfscript>
    queryString = [ "search" ];

    data = {
        "search": ""
    };
</cfscript>

<cfoutput>
    <div>
        <input wire:model="search" type="search" placeholder="Search articles...">
    </div>
</cfoutput>
```

Now when we access the page with 'search' included in the query string (*/search-articles?search=some+string*), the search property will have a default value of "some string".

In addition to this, when the user starts typing into our search field, the URL displayed in the browser will be instantly updated.


# Redirecting

Methods to redirect your users where you need.

You can redirect users in your actions using **relocate()**.

```html
<cfscript>
    function redirectToURI() {
        return relocate( uri="/some-url" );
    }

    function redirectToURL() {
        return relocate( uri="https://www.google.com" );
    }

    function redirectToEvent(){
        return relocate( event="examples.index" );
    }

    function redirectWithFlash() {
        relocate( event="example.index", persistStruct={
            confirm: "Redirect successful"
        } );
    }
</cfscript>

<cfoutput>
    <div>
        <button wire:click="redirectToURI">Redirect To URI</button>
        <button wire:click="redirectToURL">Redirect To URL</button>
        <button wire:click="redirectToEvent">Redirect To Event</button>
        <button wire:click="redirectWithFlash">Redirect With Flash</button>
    </div>
</cfoutput>
```

## Arguments

CBWIRE's **relocate()** method signature is nearly identical to ColdBox's internal *relocate()* method, except that status codes cannot be set. Otherwise, most of the arguments that ColdBox accepts can be used.

```javascript
/**
 * Relocate user browser requests to other events, URLs, or URIs.
 *
 * @event             The name of the event to relocate to, if not passed, then it will use the default event found in your configuration file.
 * @queryString       The query string or a struct to append, if needed. If in SES mode it will be translated to convention name value pairs
 * @addToken          Wether to add the tokens or not to the relocation. Default is false
 * @persist           What request collection keys to persist in flash RAM automatically for you
 * @persistStruct     A structure of key-value pairs to persist in flash RAM automatically for you
 * @ssl               Whether to relocate in SSL or not. You need to explicitly say TRUE or FALSE if going out from SSL. If none passed, we look at the even's SES base URL (if in SES mode)
 * @baseURL           Use this baseURL instead of the index.cfm that is used by default. You can use this for SSL or any full base url you would like to use. Ex: https://mysite.com/index.cfm
 * @postProcessExempt Do not fire the postProcess interceptors, by default it does
 * @URL               The full URL you would like to relocate to instead of an event: ex: URL='http://www.google.com'
 * @URI               The relative URI you would like to relocate to instead of an event: ex: URI='/mypath/awesome/here'
 *
 * @return void
 */
function relocate(
	event                = "",
	queryString          = "",
	boolean addToken     = false,
	persist              = "",
	struct persistStruct = structNew()
	boolean ssl,
	baseURL                   = "",
	boolean postProcessExempt = false,
	URL,
	URI
)
```


# WireBox

ColdBox's dependency injection framework, right there when you need it.

CBWIRE includes WireBox for pulling any dependencies you may need to use in your components, such as service objects, settings, and more.

## getInstance()

You can pull in dependencies to your component using **getInstance()**.

```html
<cfscript>
    function log() {
        var storage = getInstance( "cbfs:disks:temp" );
        storage.create( "log.txt", "CBWIRE rocks!" );
    }
</cfscript>

<cfoutput>
    <div>
        <!--- HTML goes here --->
    </div>
</cfoutput>
```

## Property Injection

You can also pull in dependencies using property injection.

```html
<cfscript>
    property name="storage" inject="cbfs:disks:temp";

    function log() {
        storage.create( "log.txt", "CBWIRE rocks!" );
    }
</cfscript>

<cfoutput>
    <div>
        <!--- HTML goes here --->
    </div>
</cfoutput>
```

## onDIComplete

If you want to act immediately after WireBox has fully constructor your component with it's dependencies, you can hook into the *onDIComplete()* method.

```html
<cfscript>
    property name="storage" inject="cbfs:disks:temp";

    function onDIComplete() {
        log.info( "CBWIRE rocks!" );
    }
</cfscript>

<cfoutput>
    <div>
        <!--- HTML goes here --->
    </div>
</cfoutput>
```


# Directives

HTML directives to make your app come alive.

CBWIRE's powerful directives allow you to listen for client side events, invoke actions, bind to data properties, and more.

The following directives can be added to your components and instruct CBWIRE how and when to update and render the component.

### wire:key

```html
<div wire:key="foo"></div>
```

Define a key name *foo* for the element. This provides a reference point for the CBWIRE DOM diffing system. Useful for adding/removing elements and keeping track of lists.

{% hint style="success" %}
If you are working with nested components and the DOM is not updating as expected, adding wire:key with a unique identifier for each child component can often resolve the issue.
{% endhint %}

### wire:click

```html
<button wire:click="foo">...</button>

<a href="" wire:click.prevent="foo">Click here</a>
```

Listens for a *click* event and invokes the *foo* action.

{% hint style="info" %}
You will want to add the .prevent [modifier](#event-modifiers) to ensure that the browser doesn't follow the link.
{% endhint %}

### wire:click.prefetch

```html
<button wire:click.prefetch="foo">...</button>
```

Listens for a *mouseEnter* event and then prefetches the result of the *foo* action. If the element is then clicked, it will swap in the prefetched result without any extra request. If it's not clicked, the cached results will be thrown away.

### wire:submit

```html
<form wire:submit.prevent="someAction">
    <button type="submit">Submit Form</button>
</form>
```

Listeners for a *submit* event on a form.

{% hint style="info" %}
You will want to add the *.prevent* [modifier](#event-modifiers) to ensure that the browser doesn't submit the form.
{% endhint %}

### wire:keydown

```html
<input wire:keydown="foo" type="text">
```

Listens for a *keyDown* event and invokes the *foo* action.

### wire:keydown.enter

```html
<input wire:keydown.enter="foo" type="text">
```

Listens for a *keyDown* event when the user hits enter and invokes the *foo* action.

### wire:foo

```html
<select wire:foo="bar"></select>
```

Listens for a *foo* event and invokes the *bar* action.

{% hint style="success" %}
You can listen to any JS event, not just those defined by CBWIRE.
{% endhint %}

### wire:model

```html
<input wire:model="foo" type="text">
```

Provided you have *data.foo* defined in your data properties, this creates a one-to-one model binding. Any time the element is updated, the value is synchronized.

### wire:model.debounce

```html
<input wire:model.debounce.1s="foo" type="text">
<input wire:model.debounce.500ms="foo" type="text">
```

The same as *wire:model="foo"* except that all input events to the element will be debounced for the specified duration. Defaults to 150 milliseconds. Useful for reducing XHR background requests during user input. You can set the milliseconds value to any numeric value.

### wire:model.defer

```html
<input wire:model.defer="foo" type="text">
```

Creates a one-to-one model binding with *data.foo* in your data properties but defers any XHR updates until an action is performed. Useful for reducing XHR requests.

### wire:model.lazy

```
<input wire:model.lazy="foo" type="text">
```

Creates a one-to-one model binding with *data.foo* in your data properties but will not perform XHR updates until an *onBlur* event is emitted. Urecommendseful for reducing XHR requests.

{% hint style="success" %}
If your input field does not require immediate updating ( such as for instant form validation), we highly recommend you use the *.lazy* modifier to reduce the number of XHR requests.
{% endhint %}

### wire:poll

```html
<div wire:poll></div>
<div wire:poll.5s></div>
<div wire:poll.5000ms></div>
<div wire:poll.5s="fooMethod"></div>
```

Performs an XHR request to re-render the elements based on a set interval. An interval can be specified in both seconds or milliseconds. You can also specify an action that you want to invoke. [*See Polling*](/3.x/template-features/polling)

### wire:init

```html
<div wire:init="foo"></div>
```

Invokes the *foo* action on your component immediately after it's rendered on the page.

### wire:loading

```html
<span wire:loading><img src="spinner.gif"></span>
```

Hides the HTML element by default and makes it visible when XHR requests are performed.

### wire:loading.class

```html
<div wire:loading.class="highlight"></div>
```

Adds the *foo* class to the HTML element while XHR requests are in transit.

### wire:loading.class.remove

```html
<div wire:loading.class.remove="highlight" class="highlight"></div>
```

Removes the *foo* class from the HTML element while XHR requests are in transit.

### wire:loading.attr

```html
<button wire:loading.attr="disabled">...</button>
```

Adds the *disabled="true"* attribute while XHR requests are in transit.

### wire:dirty

Hides the HTML element by default and makes it visible when the element's state has changed since the latest XHR request.

```html
<div wire:dirty="foo">...</div>
```

### wire:dirty.class

```html
<div wire:dirty.class="highlight">...</div>
```

Adds the *foo* class to the HTML element when the element's state has changed since the latest XHR request.

### wire:dirty.class.remove

```html
<div wire:dirty.class.remove="highlight" class="highlight">...</div>
```

Removes the *foo* class from the HTML element when the element's state has changed since the latest XHR request.

### wire:dirty.attr

```html
<button wire:dirty.attr="disabled">...</div>
```

Adds the *disabled="true"* attribute when the element's state has changed since the latest XHR request. Used in addition to *wire:target*.

### wire:target

```html
<button wire:dirty.attr="disabled" wire:target="foo">...</div>
```

Provides scoping for *wire:loading* and *wire:dirty* references, scoped to a specific action.

### wire:ignore

```html
<div wire:ignore></div>
```

Instructs CBWIRE not to update the element or child elements when updating the DOM. Useful when using third-party JavaScript libraries.

### wire:ignore.self

```html
<div wire:ignore.self></div>
```

Instructs CBWIRE to not update the element but DOES allow updates to any child elements when updating the DOM.

### wire:offline

*See* [*Offline State*](/3.x/template-features/offline-state)

## Event Modifiers

CBWIRE Directives sometimes offer "modifiers" to add extra functionality to an event. Here are the available modifiers that can be used with any event.

| Modifier       |                                                                                                                                                                                                                                  |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| stop           | Equivalent of `event.stopPropagation()`                                                                                                                                                                                          |
| prevent        | Equivalent of `event.preventDefault()`                                                                                                                                                                                           |
| self           | Only triggers an action if the event was triggered on itself. This prevents outer elements from catching events that were triggered from a child element. (Like often in the case of registering a listener on a modal backdrop) |
| debounce.300ms | Adds an Xms debounce to the handling of the action.                                                                                                                                                                              |

```html
<a href="" wire:click.prevent="someAction">Click here</a>
```

### Keydown Modifiers

To listen for specific keys on *keydown* events, you can provide the name of the key as a modifier. You can use any valid key names exposed via [KeyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) as modifiers by converting them to kebab-case.

Here is a quick list of some common ones you may need:

| Native Browser Event | Livewire Modifier |
| -------------------- | ----------------- |
| Backspace            | backspace         |
| Escape               | escape            |
| Shift                | shift             |
| Tab                  | tab               |
| ArrowRight           | arrow-right       |

```html
<input wire:keydown.page-down="foo">
```

In the above example, the *foo* action will only be called if *event.key* is equal to '*PageDown*'.


# Loading States

Show your users loading spinners, modals, and more as they wait for requests to complete.

Actions may involve a long-running process (such as completing a cart checkout) and HTML may not re-render instantly. You can help your users during the wait using Loading States. Loading States allow you to show/hide elements, add/remove classes, or toggle HTML attributes until the server responds.

{% hint style="success" %}
Loading States can make your apps feel much more responsive and user-friendly.
{% endhint %}

## Toggling Elements

Let's look at an action that takes too long.

```javascript
<cfscript>
    function addTask(){
        sleep( 5000 ); // Optimize this code yo!
    }
</cfscript>
```

We can annotate our \<div> with *wire:loading* to display *Adding Task* while the checkout action is running.

```xml
<cfoutput>
    <div>
        <button wire:click="addTask">Add Task</button>
    
        <div wire:loading>
            Adding Task...
        </div>
    </div>
</cfoutput>

<cfscript>
    function addTask(){
        sleep( 5000 ); // Optimize this code yo!
    }
</cfscript>
```

After the action completes, the *Adding Task...* output will disappear. :wave:&#x20;

## Toggling Attributes

```xml
<cfoutput>
    <div>
        <button wire:click="addTask" wire:loading.attr="disabled">
            Add Task
        </button>
    </div>
</cfoutput>
```

## Targeting Specific Actions

You can target a specific action so that the element is only visible if a specific action is loading using *wire:target*.

```html
<cfoutput>
   <div>
       <button wire:click="addTask">Add Task</button>
    
       <div wire:loading wire:target="addTask">
          Adding task...
       </div>
   </div>
</cfoutput>
```

## Delaying

If you want to avoid flickering because loading is very fast, you can add a *.delay* modifier, and it will only show up if loading takes longer than 200ms.

```html
<div wire:loading.delay>...</div>
```

If you wish, you can customize the delay duration with the following modifiers:

```xml
<div wire:loading.delay.shortest>...</div> <!-- 50ms -->
<div wire:loading.delay.shorter>...</div>  <!-- 100ms -->
<div wire:loading.delay.short>...</div>    <!-- 150ms -->
<div wire:loading.delay>...</div>          <!-- 200ms -->
<div wire:loading.delay.long>...</div>     <!-- 300ms -->
<div wire:loading.delay.longer>...</div>   <!-- 500ms -->
<div wire:loading.delay.longest>...</div>  <!-- 1000ms -->
```

## Display Property

Loading State elements are set with a CSS property of *display: inline-block;* by default. You can override this behavior by using various directive modifiers.

```xml
<div wire:loading.flex>...</div>
<div wire:loading.grid>...</div>
<div wire:loading.inline>...</div>
<div wire:loading.table>...</div>
```

## Hiding

If you want to display an element except during a loading state, you can apply the *wire:loading.remove* directive.

<pre class="language-xml"><code class="lang-xml">&#x3C;cfoutput>
<strong>    &#x3C;div>
</strong>        &#x3C;button wire:click="addTask">Add Task&#x3C;/button>
    
        &#x3C;div wire:loading.remove>
            Click 'Add Task'
        &#x3C;/div>
    &#x3C;/div>
&#x3C;/cfoutput>
</code></pre>


# Polling

Update your components automatically based on a set time interval.

You can add a **wire:poll** directive to your elements to poll for changes using a set interval. The default interval is set to poll every 2 seconds.

```xml
<div wire:poll></div>
```

You can append a different interval time to your directive as well.

```xml
<div wire:poll.5s> <!-- poll every 5 seconds --> </div>
```

{% hint style="success" %}
Polling for changes over AJAX can be a reasonable alternative to strategies such as Pusher or WebSockets.&#x20;
{% endhint %}

## Method Invocation

If you would like to invoke a method during each poll interval, you can do so by specifying a method name.

```xml
<cfoutput>
    <div>
        <div wire:poll="refreshTasks"></div>
    </div>
</cfoutput>

<cfscript>
    function refreshTask() {}
</cfscript>
```

## Stop Polling

If you want to stop polling, you can no longer render the HTML element by omitting the wire:poll directive.

```html
<cfif shouldPoll>
    <div wire:poll="refreshTasks"></div>
<cfelse>
    <div><!-- No more polling --></div>
</cfif>
```


# Prefetching

Prefetch component updates as the user mouses over HTML elements.

CBWIRE has a feature called prefetching which will prefetch the rendering of an action and store the HTML client-side without rendering the update to the DOM until the action is performed.&#x20;

Consider the example below. Notice we have added a *.prefetch* modifier to our *wire:click* directive.

```html
<button wire:click.prefetch="togglePreview">Show Preview</button>
```

```xml
<!--- ./wires/ShowImage.cfm --->
<cfoutput>
<div>
    <button wire:click.prefetch="togglePreview">Show Preview</button>

    <cfif showPreview>
        <!--- Preview goes here --->
    </cfif>
</div>
</cfoutput>

<cfscript>
    data = {
        "showPreview": false
    };

    function togglePreview(){
        data.showPreview = true;
    }
</cfscript>
```

{% hint style="info" %}
In the example here, the *togglePreview* action will be prefetched and invoked when the user mouses over the button. The results of the fetch are not displayed until the user clicks the 'Show Preview' button.
{% endhint %}

{% hint style="warning" %}
Prefetching works well for actions that do not perform any side effects, such as mutating session data or writing to a database. If the action you are "pre-fetching" does have side effects, you may encounter unpredictable results.
{% endhint %}


# Offline State

Display modals, alerts, or any HTML when your users are offline.

CBWIRE provides offline state management, making it easy to toggle UI elements when the user is offline or online.

You can use *wire:offline* to display elements when CBWIRE detects that the user is offline.

```html
<div wire:offline><!-- Oh no, you're offline --></div>
```

You can append *.class* to your *wire:offline* directive and specify a CSS class to toggle when the user is offline.

```html
<div wire:offline.class="online" class="online"></div>
```

Use *.remove* to specify classes you want to be removed when offline.

```html
<div wire:offline.class.remove="im-online" class="im-online"></div>
```


# Defer Loading

Improve user's perceived load times by using deferred loading.

CBWIRE allows you to call an action immediately once your component is rendered.

You can do this by adding the *wire:init* directive to your component's outer element.

```html
<cfoutput>
<div wire:init="loadTasks">
    <ul>
        <cfloop array="#args.tasks#" index="task">
            <li>#task#</li>
        </cfloop>
    </ul>
</div>
</cfoutput>

<cfscript>
    data = {
        "tasks": []
    };
    
    function loadTasks() {
        data.tasks = getInstance( "TaskService" ).asMemento().get()
    }
</cfscript>
```

{% hint style="info" %}
This can be helpful in cases where you don't want to hold up the page from fully loading but want to load some data immediately after the page load.
{% endhint %}


# Dirty State

Display HTML elements as data properties change but haven't been updated server-side yet.

In some cases, providing feedback that content has changed and needs to be synchronized with the back end may be helpful.

For input that uses *wire:model*, or *wire:model.lazy*, you can use *wire:dirty* along with *wire:target* to display HTML elements if a property has been changed client-side but not yet synced with the server.

```html
<div>
    <input wire:model.lazy="foo">
    <div wire:dirty wire:target="foo">Foo not synced yet</div>
</div>
```

## Class Modifier

Adding the *.class* modifier allows you to add a class to the element when dirty.

```html
<div>
    <input wire:dirty.class="border-red-500" wire:model.lazy="foo">
</div>
```

You can perform the inverse and remove classes by adding the *.remove* modifier.

```html
<div>
    <input wire:dirty.class.remove="bg-green-200" class="bg-green-200" wire:model.lazy="foo">
</div>
```


# ContentBox CMS

Use CBWIRE with ContentBox to provide your users a modern CMS-powered app.

[ContentBox](https://contentbox.ortusbooks.com/) is a professional open source modular CMS (Content Management System) that allows you to easily build websites, blogs, wikis, complex web applications and even power mobile or cloud applications. Built with a secure and flexible modular core, designed to scale, and combined with world-class support, ContentBox will get your projects out the door in no time.

## Installation

{% hint style="info" %}
You need to install CBWIRE version 2.3.3 or later to use CBWIRE and ContentBox.
{% endhint %}

In the root of your ContentBox application, install CBWIRE using [CommandBox](https://commandbox.ortusbooks.com/). The example below installs the latest bleeding-edge version.

```
box install cbwire@be
```

{% hint style="info" %}
Once installed, you must restart your app using *?fwreinit=\[your secret key]*.
{% endhint %}

{% hint style="warning" %}
Please ensure that CBWIRE is installed under */modules/cbwire* from the root of your project. It should be installed there by default. Installing CBWIRE elsewhere can cause errors within a ContentBox application.
{% endhint %}

## Theme Integration

{% hint style="info" %}
You will need to use a custom theme to integrate with CBWIRE.
{% endhint %}

If you want to use a theme included with ContentBox or one you've pulled down from ForgeBox, you can copy the theme code to the folder *modules\_app/contentbox-custom/\_themes*.

Once CBWIRE is installed, you should have access to the CBWIRE core methods. You can reference these within your layout and theme templates.

* **wireStyles()** - Pulls in required styling for CBWIRE
* **wireScripts()** - Pulls in required JavaScript assets for CBWIRE
* **wires()** - renders a component (reactive UI element) you create

In your theme layout, you need to place **wireStyles()** within your \<head> tags, **wireScripts()** before the end of \</body>, and you can call **wire()** to include your reactive UI Wires where needed.

```html
<!--- modules_app/contentbox-custom/_themes/cbwireTheme/layouts/blog.cfm --->
<cfoutput>
<!--- Global Layout Arguments --->
<cfparam name="args.print" default="false">
<cfparam name="args.sidebar" default="true">

<!DOCTYPE html>
<html lang="en">
<head>
	<!--- Page Includes --->
	#cb.quickView( "_blogIncludes" )#

	<!--- ContentBoxEvent --->
	#cb.event( "cbui_beforeHeadEnd" )#

	<!--- PULL IN CBWIRE STYLING --->
	#wireStyles()#
</head>
<body>
	<!--- ContentBoxEvent --->
	#cb.event( "cbui_afterBodyStart" )#

	<!--- Header --->
	#cb.quickView( '_header' )#

	<!--- ContentBoxEvent --->
	#cb.event( "cbui_beforeContent" )#

	<!--- Main View --->
	#cb.mainView( args=args )#
	
	<!--- INCLUDE REACTIVE NEWSLETTER SIGNUP COMPONENT --->
	#wire( "NewsletterSignup", {
		validate: true
	} )#

	<!--- ContentBoxEvent --->
	#cb.event( "cbui_afterContent" )#

	#cb.quickView( view='_footer' )#

	<!--- ContentBoxEvent --->
	#cb.event( "cbui_beforeBodyEnd" )#

	<!--- PULL IN CBWIRE JAVASCRIPT ASSETS --->
	#wireScripts()#
</body>
</html>
</cfoutput>
```

You can also reference the **wire()** method within your views.

```html
<!--- modules_app/contentbox-custom/_themes/cbwireTheme/views/index.cfm --->
<div class="row">
    <div class="col-12">
        #wire( "ContactForm" )#
    </div>
</div>
```


# SPAs with Turbo

Create single-page-like applications (SPAs) with little-to-no JavaScript in record time.

CBWIRE has built-in support for [Turbo](https://turbo.hotwired.dev/). Turbo is an open-source library that accelerates links and form submissions by negating the need for full-page reloads. With Turbo, you get all the following included:

* Links and form submissions are performed in the background using AJAX instead of performing full-page reloads
* Browse history management, so clicking the back and forward buttons in the browser work as expected
* Internal caching improves perceived performance by showing temporary previews during network requests and while the page is updated
* Built-in progress bar
* Pre-load Links
* And much more!

CBWIRE and Turbo allow you to build single-page applications in record time quickly.

## Enabling Turbo

You can enable Turbo with the *enableTurbo* [configuration setting](/3.x/configuration), which automatically wires up everything needed to start using Turbo. Once enabled, links and form submissions will automatically be performed in the background via AJAX instead of performing full-page reloads.&#x20;

You can alternatively perform a [manual installation](#manual-installation) of Turbo instead.

```javascript
// File: ./config/ColdBox.cfc
component{
    function configure() {
        moduleSettings = {
            "cbwire" = {
                "enableTurbo": true
            }
        };
     }
}

```

## Manual Installation

{% hint style="info" %}
Use the manual installation when you want more control over where Turbo is included within your HTML.
{% endhint %}

### npm

You can install Turbo by running the following `npm` command in the root of your project.

```bash
npm i @hotwired/turbo
```

Then you can require or import Turbo.

```javascript
import * as Turbo from "@hotwired/turbo"
```

### Skypack

To avoid manual installation, there is also a [Skypack](https://www.skypack.dev/view/@hotwired/turbo) available which you can add to the \<head>\</head> of your layout.

```html
<script type="module">
    import hotwiredTurbo from 'https://cdn.skypack.dev/@hotwired/turbo';
</script>
```

### Turbo Plugin

To work correctly, include the Turbo plugin below your *wireScripts()* call in your layout.

```javascript
    #wireScripts()#
    <script src="https://cdn.jsdelivr.net/gh/livewire/turbolinks@v0.1.x/dist/livewire-turbolinks.js" data-turbolinks-eval="false" data-turbo-eval="false"></script>
</body>
```

{% hint style="info" %}
Note: You MUST have either the *data-turbolinks-eval="false"* or *data-turbo-eval="false"* attributes added to the script tag (having both won't hurt).
{% endhint %}

## Progress Bar

During Turbo navigation, the browser will not display its native progress indicator. Turbo installs a CSS-based progress bar to provide feedback while issuing a request.

The progress bar is enabled by default. It appears automatically for any page that takes longer than 500ms to load.

The progress bar is a `<div>` element with the class name `turbo-progress-bar`. Its default styles appear first in the document and can be overridden by rules that come later.

For example, the following CSS will result in a thick green progress bar:

```css
.turbo-progress-bar {
    height: 5px;
    background-color: green;
}
```

In your layout file, you can include the progress bar like so:

```html
<!-- ./layouts/Main.cfm -->
<cfoutput>
<html>
    <head>
        <title>Turbo Page</title>
        #wireStyles()#
    </head>
    <body>
        <div class="turbo-progress-bar"></div>
        <div class="mainContent">
            Some content here
        </div>
        #wireScripts()#
    </body>
</html>
</cfoutput>
```

## Preload Links

Preload links into Turbo Drive’s cache using *data-turbo-preload*.

```html
<a href="/" data-turbo-preload>Home</a>
```

This will make page transitions feel lightning fast by providing a preview of a page even before the first visit. Use it to preload the most important pages in your application.&#x20;

{% hint style="warning" %}
Avoid over usage, as it will lead to loading content that is not needed.
{% endhint %}


# AlpineJS

Alpine JS brings simple client-side reactivity when you need it and integrates beautifully with CBWIRE.

Many page interactions don't warrant a full server roundtrip, such as toggling a modal or a hidden element. In these instances, we recommend using [AlpineJS](https://alpinejs.dev/).

{% hint style="info" %}
AlpineJS allows you to add JavaScript behavior directly into your markup in a declarative way. If you are familiar with VueJS, Alpine should feel similar.
{% endhint %}

## Installation

```html
<head>
    <script src="//unpkg.com/alpinejs" defer></script>
    <!-- The "defer" attribute is important to ensure Alpine waits for CBWIRE to load first. -->
</head>
```

For more installation information, visit [Alpine Docs](https://alpinejs.dev/).

## Templates

Below is an example of using [AlpineJS](https://alpinejs.dev/) to toggle a list on the page.

```html
<div>
    <div x-data="{ open: false }">
        <button @click="open = true">Show More...</button>
 
        <ul x-show="open" @click.away="open = false">
            <li><button wire:click="archive">Archive</button></li>
            <li><button wire:click="delete">Delete</button></li>
        </ul>
    </div>
</div>
```

## Shared State

CBWIRE has a powerful *entangle()* method that allows you to "entangle" a CBWIRE and AlpineJS data property. With entanglement, both client-side and server-side properties are instantly synchronized, regardless of whether the value was changed in CFML or client-side using JavaScript.

{% hint style="warning" %}
You need CBWIRE v2.3.6 or greater to use *entangle()*.
{% endhint %}

{% hint style="success" %}
This provides data model binding both client-side and server-side.
{% endhint %}

Consider this simple Counter component:

```html
<!--- ./wires/Counter.cfm --->
<cfscript>
    data = {
        "counter": 0
    };

    function increment() {
        data.counter += 1;
    }
</cfscript>

<cfoutput>
    <div x-data="{ counter: #entangle( 'counter' )# }">
        <div>CBWIRE value: #counter#</div>
        <div>AlpineJS value: <span x-html="counter"></span></div>
        
        <button
            wire:click="increment"
            type="button">Increment with CBWIRE</button>
        
        <button
            @click="counter += 1"
            type="button">Increment with AlpineJS</button>
    </div>
</cfoutput>
```

We define an AlpineJS property named *counter and* then call the built-in CBWIRE method *entangle()*, passing it the name of the server-side data property we want to bind with.

```html
<div x-data="{ counter: #entangle( 'counter' )# }">
```

Next, we are incrementing our Counter in two separate ways:

* Incrementing the counter by calling the *increment()* action using CBWIRE
* Incrementing the AlpineJS property *counter* in JavaScript, triggering an immediate update to the server and re-rendering of the component.

```html
<button wire:click="increment" type="button">Increment with CBWIRE</button>
<button @click="counter += 1" type="button">Increment with AlpineJS</button>
```

Updating CBWIRE server-side on every AlpineJS property change is optional. You can also delay the server-side updates until the next CBWIRE request that goes out by chaining a *.defer* modifier like so.

```html
<div x-data="{ counter: #entangle( 'counter' )#.defer }">
```


# Introduction

CBWIRE is a ColdBox module that uses Livewire and Alpine.js to help you build modern, reactive BoxLang and CFML applications in record time without building backend APIs.

<figure><img src="https://2870983625-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fjkd9Hn6eBWZAtkh46wPO%2Fuploads%2Fgit-blob-453d9ecff4eaafa701d5c364a7dcd56a938bcc06%2FCBWIRE-Logo.png?alt=media" alt=""><figcaption></figcaption></figure>

CBWIRE revolutionizes BoxLang and CFML web development by bringing reactive UI capabilities directly to your server-side code. Build dynamic, interactive interfaces without writing JavaScript, managing APIs, or dealing with complex frontend frameworks.

## Your First Component

Let's create a reactive counter component to demonstrate CBWIRE's power. Download and install [CommandBox](https://www.ortussolutions.com/products/commandbox), then run these commands:

```bash
mkdir cbwire-playground --cd
install cbwire@4
install commandbox-boxlang
coldbox create app
server start cfengine=boxlang javaVersion=openjdk21_jdk
```

### 1. Add Component to Layout

Insert a counter component into your Main layout using `wire("Counter")`:

{% tabs %}
{% tab title="BoxLang" %}

```html
<!-- layouts/Main.bxm -->
<bx:output>
<!doctype html>
<html>
    <head>
        <title>CBWIRE Demo</title>
    </head>
    <body>
        <!-- Insert our reactive counter -->
        #wire("Counter")#
    </body>
</html>
</bx:output>
```

{% endtab %}

{% tab title="CFML" %}

```html
<!-- layouts/Main.cfm -->
<cfoutput>
<!doctype html>
<html>
    <head>
        <title>CBWIRE Demo</title>
    </head>
    <body>
        <!-- Insert our reactive counter -->
        #wire("Counter")#
    </body>
</html>
</cfoutput>
```

{% endtab %}
{% endtabs %}

### 2. Create the Component

Define your Counter [component](/cbwirev4/the-essentials/components):

{% tabs %}
{% tab title="BoxLang" %}

```javascript
// wires/Counter.bx
class extends="cbwire.models.Component" {
    
    data = {
        "counter": 0
    };

    function increment() {
        data.counter++;
    }
    
    function decrement() {
        data.counter--;
    }
}
```

{% endtab %}

{% tab title="CFML" %}

```javascript
// wires/Counter.cfc
component extends="cbwire.models.Component" {
    
    data = {
        "counter" = 0
    };

    function increment() {
        data.counter++;
    }
    
    function decrement() {
        data.counter--;
    }
}
```

{% endtab %}
{% endtabs %}

### 3. Create the Template

Define the counter [template](/cbwirev4/the-essentials/templates):

{% tabs %}
{% tab title="BoxLang" %}

```html
<!-- wires/counter.bxm -->
<bx:output>
<div>
    <h1>Count: #counter#</h1>
    <button wire:click="increment">+</button>
    <button wire:click="decrement">-</button>
</div>
</bx:output>
```

{% endtab %}

{% tab title="CFML" %}

```html
<!-- wires/counter.cfm -->
<cfoutput>
<div>
    <h1>Count: #counter#</h1>
    <button wire:click="increment">+</button>
    <button wire:click="decrement">-</button>
</div>
</cfoutput>
```

{% endtab %}
{% endtabs %}

### 4. See the Magic

Navigate to your application in the browser. Click the + and - buttons to see the counter update instantly without page refreshes or JavaScript code! 🤯

![](https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEWvXvmxEDxwnAJzKYkxz%2Fuploads%2FPESERLoILEJOeO4yXCCn%2F2022-02-08%2016.02.25.gif?alt=media\&token=7846eb9)

## How Does It Work?

CBWIRE seamlessly bridges your server-side BoxLang or CFML code with dynamic frontend behavior:

1. **Initial Render**: CBWIRE renders your component with its default data values
2. **User Interaction**: When a user clicks a button with `wire:click`, Livewire.js captures the event
3. **Server Request**: The interaction triggers an AJAX request to your CBWIRE component's action method
4. **Data Processing**: Your server-side action method processes the request and updates component data
5. **Response & Update**: The updated HTML is sent back and Livewire.js efficiently updates only the changed parts of the DOM

This approach gives you the responsiveness of modern JavaScript frameworks while keeping your logic in familiar server-side code.

## Why CBWIRE?

Building our reactive counter with CBWIRE meant we:

* ✅ **Developed a responsive interface** without writing JavaScript
* ✅ **Avoided creating backend APIs** - everything stays in your ColdBox application
* ✅ **Eliminated page refreshes** while maintaining server-side control
* ✅ **Skipped complex build processes** like webpack or JavaScript compilation
* ✅ **Stayed in our BoxLang/CFML environment** using familiar syntax and patterns

## Better With Alpine.js

While CBWIRE handles server communication beautifully, sometimes you need instant client-side updates without server round-trips. This is where [Alpine.js](https://alpinejs.dev/) shines - a lightweight JavaScript framework designed to work perfectly with Livewire (and therefore CBWIRE).

Let's enhance our counter to use Alpine.js for instant updates and add persistence:

{% tabs %}
{% tab title="BoxLang" %}

```javascript
// wires/Counter.bx
class extends="cbwire.models.Component" {   
    
    data = {
        "counter": 0
    };

    function onMount() {
        data.counter = session.counter ?: 0;
    }
    
    function save(counter) {
        session.counter = arguments.counter;
    }
}
```

{% endtab %}

{% tab title="CFML" %}

```javascript
// wires/Counter.cfc
component extends="cbwire.models.Component" {   
    
    data = {
        "counter" = 0
    };

    function onMount() {
        data.counter = session.counter ?: 0;
    }
    
    function save(counter) {
        session.counter = arguments.counter;
    }
}
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="BoxLang" %}

```html
<!-- wires/counter.bxm -->
<bx:output>
<div 
    x-data="{
        counter: $wire.counter,
        increment() { this.counter++; },
        decrement() { this.counter--; },
        async save() {
            await $wire.save(this.counter);
        }
    }"
    wire:ignore.self>
    
    <h1>Count: <span x-text="counter"></span></h1>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
    <button @click="save">Save</button>
</div>
</bx:output>
```

{% endtab %}

{% tab title="CFML" %}

```html
<!-- wires/counter.cfm -->
<cfoutput>
<div 
    x-data="{
        counter: $wire.counter,
        increment() { this.counter++; },
        decrement() { this.counter--; },
        async save() {
            await $wire.save(this.counter);
        }
    }"
    wire:ignore.self>
    
    <h1>Count: <span x-text="counter"></span></h1>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
    <button @click="save">Save</button>
</div>
</cfoutput>
```

{% endtab %}
{% endtabs %}

Now the counter updates instantly on the client side, but only makes server requests when "Save" is clicked to persist the value. The `onMount()` method loads the saved counter from the session on page load. Using `$wire`, Alpine.js communicates seamlessly with your CBWIRE component.

This combination gives you complete control: instant UI feedback when needed, and server communication when you want to persist data or run complex business logic.

## What's Next?

Ready to dive deeper? Explore these essential concepts:

* [**Getting Started**](/cbwirev4/getting-started): Complete installation and setup guide
* [**Components**](/cbwirev4/the-essentials/components): Learn how to build and organize CBWIRE components
* [**Templates**](/cbwirev4/the-essentials/templates): Master template syntax and data binding
* [**Actions**](/cbwirev4/the-essentials/actions): Handle user interactions and component methods
* [**Properties**](/cbwirev4/the-essentials/properties): Understand data binding and reactivity
* [**Events**](/cbwirev4/the-essentials/events): Communicate between components and handle lifecycle events

## Credits

CBWIRE leverages the incredible JavaScript libraries [Livewire](https://laravel-livewire.com/) and [Alpine.js](https://alpinejs.dev/) for DOM diffing and client-side functionality. CBWIRE wouldn't exist without the brilliant work of [Caleb Porzio](https://x.com/calebporzio), creator of both Livewire and Alpine.js. CBWIRE brings these powerful tools into the ColdBox and BoxLang/CFML ecosystem.

The CBWIRE module is developed and maintained by [Grant Copley](https://twitter.com/grantcopley), [Luis Majano](https://twitter.com/lmajano), and the team at [Ortus Solutions](https://www.ortussolutions.com/).

## Project Support

Please consider becoming one of our [Patreon supporters](https://www.patreon.com/ortussolutions) to help us continue developing and improving CBWIRE.


# How It Works

CBWIRE bridges the gap between server-side BoxLang/CFML code and dynamic frontend experiences. Understanding how this magic happens will help you build better applications and debug issues when they arise.

## The CBWIRE Architecture

CBWIRE consists of four main parts working together:

1. **Server-side Components** - Your BoxLang/CFML classes that handle data and business logic
2. **Livewire.js** - Client-side JavaScript that manages DOM updates and server communication
3. **Alpine.js** - Lightweight JavaScript framework for client-side interactivity and state management
4. **ColdBox Integration** - The glue that connects everything within the ColdBox framework

## Component Lifecycle

Let's trace through what happens when a CBWIRE component is rendered and interacted with:

### Initial Page Load

When a user first requests a page containing CBWIRE components:

1. **Component Instantiation**: CBWIRE creates an instance of your component class
2. **Data Initialization**: The `data` struct is populated with default values
3. **Mount Lifecycle**: If present, the `onMount()` method executes
4. **Template Rendering**: Your component's template is rendered with current data values
5. **HTML Generation**: The final HTML is sent to the browser with embedded metadata

```html
<!-- Example rendered output -->
<div wire:id="abc123" wire:data='{"counter":0}'>
    <h2>Counter: 0</h2>
    <button wire:click="increment">+</button>
</div>
```

### User Interaction Flow

When a user interacts with your component (clicks a button, submits a form, etc.):

<figure><img src="https://2870983625-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fjkd9Hn6eBWZAtkh46wPO%2Fuploads%2Fgit-blob-a3469ec236f5360e9b86b1459cb5736425b08205%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

1. **Event Capture**: Livewire.js intercepts the DOM event (click, input change, form submit)
2. **Request Preparation**: The client serializes current component state and the action to perform
3. **Server Request**: An AJAX request is sent to CBWIRE's update endpoint
4. **Component Hydration**: CBWIRE recreates your component instance from the serialized state
5. **Action Execution**: Your component method runs with the current data context
6. **Data Updates**: Component data properties are modified by your action method
7. **Re-rendering**: The template is re-rendered with updated data
8. **Response Generation**: New HTML and updated state are sent back to the client
9. **DOM Diffing**: Livewire.js compares old and new HTML, updating only changed elements
10. **UI Update**: The page updates without a full refresh

## Request Anatomy

Here's what a typical CBWIRE request looks like:

### Outgoing Request

```javascript
// POST /cbwire/updates
{
    "fingerprint": {
        "id": "abc123",
        "name": "counter",
        "locale": "en",
        "path": "/",
        "method": "GET"
    },
    "serverMemo": {
        "data": {"counter": 5},
        "checksum": "xyz789"
    },
    "updates": [
        {
            "type": "callMethod",
            "payload": {
                "method": "increment",
                "params": []
            }
        }
    ]
}
```

### Server Response

```javascript
{
    "effects": {
        "html": "<div wire:id=\"abc123\"...>...</div>",
        "dirty": ["counter"]
    },
    "serverMemo": {
        "data": {"counter": 6},
        "checksum": "abc456"
    }
}
```

## Data Binding Deep Dive

CBWIRE provides several ways to bind data between your template and component:

### One-Way Data Binding

Data flows from component to template automatically:

{% tabs %}
{% tab title="BoxLang" %}

```javascript
// wires/UserProfile.bx
class extends="cbwire.models.Component" {
    data = {
        "user": {
            "name": "John Doe",
            "email": "john@example.com"
        }
    };
}
```

{% endtab %}

{% tab title="CFML" %}

```javascript
// wires/UserProfile.cfc
component extends="cbwire.models.Component" {
    data = {
        "user" = {
            "name" = "John Doe",
            "email" = "john@example.com"
        }
    };
}
```

{% endtab %}
{% endtabs %}

```html
<!-- Template automatically reflects data changes -->
<div>
    <h1>Welcome, #data.user.name#</h1>
    <p>Email: #data.user.email#</p>
</div>
```

### Two-Way Data Binding

Form inputs can automatically sync with component data:

```html
<!-- Changes to input automatically update component data -->
<input type="text" wire:model="user.name" />
<input type="email" wire:model="user.email" />
```

When users type in these fields, CBWIRE automatically updates your component's data properties in real-time.

## Action Methods

Actions are public methods in your component that can be called from the template:

{% tabs %}
{% tab title="BoxLang" %}

```javascript
// wires/TodoList.bx
class extends="cbwire.models.Component" {
    data = {
        "todos": [],
        "newTodo": ""
    };
    
    function addTodo() {
        if (data.newTodo.trim().len()) {
            data.todos.append({
                "id": createUUID(),
                "text": data.newTodo,
                "completed": false
            });
            data.newTodo = "";
        }
    }
    
    function toggleTodo(todoId) {
        data.todos.each(function(todo) {
            if (todo.id == arguments.todoId) {
                todo.completed = !todo.completed;
            }
        });
    }
    
    function removeTodo(todoId) {
        data.todos = data.todos.filter(function(todo) {
            return todo.id != todoId;
        });
    }
}
```

{% endtab %}

{% tab title="CFML" %}

```javascript
// wires/TodoList.cfc
component extends="cbwire.models.Component" {
    data = {
        "todos" = [],
        "newTodo" = ""
    };
    
    function addTodo() {
        if (data.newTodo.trim().len()) {
            data.todos.append({
                "id" = createUUID(),
                "text" = data.newTodo,
                "completed" = false
            });
            data.newTodo = "";
        }
    }
    
    function toggleTodo(todoId) {
        data.todos.each(function(todo) {
            if (todo.id == arguments.todoId) {
                todo.completed = !todo.completed;
            }
        });
    }
    
    function removeTodo(todoId) {
        data.todos = data.todos.filter(function(todo) {
            return todo.id != todoId;
        });
    }
}
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="BoxLang" %}

```html
<!-- Template calling various action methods -->
<bx:output>
<div>
    <input type="text" wire:model="newTodo" placeholder="Add a todo...">
    <button wire:click="addTodo">Add</button>
    
    <ul>
        <bx:loop array="#data.todos#" index="todo">
            <li wire:key="todo-#todo.id#">
                <input type="checkbox" wire:click="toggleTodo('#todo.id#')" #todo.completed ? 'checked' : ''#>
                <span class="#todo.completed ? 'completed' : ''#">#todo.text#</span>
                <button wire:click="removeTodo('#todo.id#')">Delete</button>
            </li>
        </bx:loop>
    </ul>
</div>
</bx:output>
```

{% endtab %}

{% tab title="CFML" %}

```html
<!-- Template calling various action methods -->
<cfoutput>
<div>
    <input type="text" wire:model="newTodo" placeholder="Add a todo...">
    <button wire:click="addTodo">Add</button>
    
    <ul>
        <cfloop array="#data.todos#" index="todo">
            <li wire:key="todo-#todo.id#">
                <input type="checkbox" wire:click="toggleTodo('#todo.id#')" #todo.completed ? 'checked' : ''#>
                <span class="#todo.completed ? 'completed' : ''#">#todo.text#</span>
                <button wire:click="removeTodo('#todo.id#')">Delete</button>
            </li>
        </cfloop>
    </ul>
</div>
</cfoutput>
```

{% endtab %}
{% endtabs %}

## State Management

CBWIRE's state management is where the magic happens - it seamlessly maintains your component's data across user interactions while keeping everything secure and performant.

### State Serialization: The Journey of Your Data

Every time a user interacts with your component, CBWIRE performs an intricate dance of data serialization. Your component's `data` struct becomes a JSON payload that travels between client and server, maintaining perfect synchronization.

```javascript
// Your component data...
data = {
    "user": {"name": "Sarah", "role": "admin"},
    "products": [
        {"id": 1, "name": "Widget", "price": 29.99},
        {"id": 2, "name": "Gadget", "price": 49.99}
    ],
    "cartTotal": 0
};

// Becomes this serialized state
{
    "data": {
        "user": {"name": "Sarah", "role": "admin"},
        "products": [...],
        "cartTotal": 0
    },
    "checksum": "abc123def456"
}
```

But here's the clever part: **only your public data properties make the journey**. Private variables, computed properties, and sensitive information stay safely on the server where they belong.

```javascript
// This travels to the client
data = {"publicInfo": "visible"};

// These stay on the server
variables.secretKey = "hidden";
variables.expensiveCalculation = computeComplexData();
```

### State Security: Fort Knox for Your Data

CBWIRE doesn't just send your data into the wild west of the internet unprotected. Every state payload includes a cryptographic checksum - think of it as a tamper-evident seal on your data.

When a request comes back to the server, CBWIRE immediately verifies this checksum. If someone has tried to modify the data in transit or inject malicious content, the checksum won't match and the request gets rejected faster than you can say "security breach."

```javascript
// Client tries to modify data maliciously
{
    "data": {"isAdmin": true}, // ← Nice try, hacker!
    "checksum": "originalChecksum" // ← This won't match anymore
}
// Result: Request rejected, component stays safe
```

**Pro tip**: Never store sensitive information like passwords, API keys, or financial data in your component's `data` struct. Use server-side storage instead:

```javascript
// ❌ Bad - exposed to client
data = {
    "userName": "john",
    "creditCard": "4111-1111-1111-1111" // Yikes!
};

// ✅ Good - sensitive data stays server-side
data = {
    "userName": "john",
    "hasPaymentMethod": true
};
// Store credit card in encrypted session or database
session.encryptedPaymentInfo = encryptData(creditCardNumber);
```

### State Optimization: Speed Through Smart Design

The beauty of CBWIRE's state management lies in its efficiency. Unlike traditional frameworks that might send entire page worth of data, CBWIRE only transmits what's actually changed.

Here's how to keep your components lightning-fast:

**Keep it lean**: Your component data should be focused and minimal. Think of it as packing for a trip - only bring what you absolutely need.

```javascript
// ❌ Heavy - will slow down every request
data = {
    "allUsers": getUserService().getAllUsers(), // 10,000 users!
    "fullProductCatalog": getProductService().getAll(), // Another 5,000 items!
    "searchTerm": ""
};

// ✅ Light - fast and focused
data = {
    "searchResults": [], // Empty until needed
    "searchTerm": "",
    "currentPage": 1
};

function search() {
    // Load data only when needed
    data.searchResults = getUserService().search(data.searchTerm);
}
```

**Smart storage strategies**: Use the right tool for the job. Component state is for UI-related data that changes frequently. Everything else belongs in more appropriate storage.

```javascript
// Component state: UI-focused, changes often
data = {
    "currentStep": 1,
    "isLoading": false,
    "selectedItems": []
};

// Session: User-specific, persists across requests
session.userPreferences = {"theme": "dark", "language": "en"};

// Cache: Expensive computations, shared across users  
cache.put("popularProducts", getExpensiveProductList(), 60);

// Database: Permanent data, complex relationships
productService.save(productData);
```

This thoughtful approach to state management is what makes CBWIRE applications feel instantly responsive while maintaining the security and reliability you expect from server-side code.

## Security Model

CBWIRE includes several security features:

### CSRF Protection

* Optional CSRF tokens prevent cross-site request forgery
* Tokens are automatically managed when enabled

### Method Authorization

```javascript
// Only public methods can be called from templates
public function allowedAction() { }

private function protectedAction() { } // Cannot be called via wire:click
```

### Data Validation

```javascript
function updateProfile(name, email) {
    // Always validate input data
    if (!isValid("email", arguments.email)) {
        throw("Invalid email address");
    }
    // Process validated data
}
```

## Debugging CBWIRE Applications

### Common Issues and Solutions

**Component not updating?**

* Check browser console for JavaScript errors
* Verify CBWIRE assets are loaded
* Ensure action methods are public

**Data not persisting?**

* Remember: each request creates a fresh component instance
* Use session, cache, or database for persistent data
* Check if data properties are being overwritten

**Performance problems?**

* Minimize data sent to client
* Use `wire:key` for list items
* Avoid heavy computations in templates

### Development Tools

* Browser developer tools show CBWIRE requests
* Server logs contain component errors
* ColdBox debugger shows component lifecycle

## Advanced Concepts

### Component Communication

Components can communicate through events:

```javascript
// Emit events from one component
emit("userUpdated", {"userId": 123});

// Listen for events in other components
listeners = {
    "userUpdated": "handleUserUpdate"
};

function handleUserUpdate(data) {
    // React to user update
}
```

### Alpine.js Integration

Combine CBWIRE with Alpine.js for optimal UX:

```html
<!-- Alpine handles client-side interactions -->
<div x-data="{ count: $wire.counter }">
    <span x-text="count"></span>
    <button @click="count++" x-on:click.debounce.500ms="$wire.save(count)">+</button>
</div>
```

### Custom Directives

Extend CBWIRE with custom behavior:

```html
<!-- Custom loading states -->
<div wire:loading.class="opacity-50">
    Content becomes transparent while updating
</div>

<!-- Conditional visibility -->
<div wire:loading wire:target="save">
    Saving...
</div>
```

Understanding these concepts will help you build robust, efficient CBWIRE applications that provide excellent user experiences while maintaining clean, server-side code.


# Getting Started

CBWIRE brings reactive UI capabilities to your BoxLang and CFML applications, making it easy to build dynamic interfaces without complex JavaScript frameworks. This guide will help you set up CBWIRE and create your first reactive component.

## System Requirements

Before installing CBWIRE, ensure your system meets these requirements:

### BoxLang Requirements

* **BoxLang 1.0+**
* **CBWIRE 4.1+** (BoxLang support was introduced in version 4.1)
* **OpenJDK 21** (required for BoxLang)
* **ColdBox 6+**
* **Required modules:**
  * [bx-compat-cfml](https://forgebox.io/view/bx-compat-cfml) - CFML compatibility layer
  * [bx-esapi](https://forgebox.io/view/bx-esapi) - Security encoding functions

### CFML Requirements

* **Adobe ColdFusion 2021+** or **Lucee 5+**
* **ColdBox 6+**

## Installation

CBWIRE is distributed through ForgeBox and can be installed using CommandBox.

### Install CommandBox

If you don't have CommandBox installed, download it from [ortussolutions.com/products/commandbox](https://www.ortussolutions.com/products/commandbox).

### Install CBWIRE

Navigate to your ColdBox application root and run:

```bash
box install cbwire@4
```

For the latest development version:

```bash
box install cbwire@be
```

## BoxLang Setup

BoxLang applications require additional configuration to work with CBWIRE. The easiest way to set this up is by creating a `server.json` file in your project root:

```json
{
    "app": {
        "cfengine": "boxlang",
        "serverHomeDirectory": ".engine/boxlang"
    },
    "web": {
        "rewrites": {
            "enable": "true"
        }
    },
    "JVM": {
        "javaVersion": "openjdk21_jdk"
    },
    "scripts": {
        "onServerInitialInstall": "install bx-compat-cfml,bx-esapi"
    }
}
```

This configuration automatically:

* Sets BoxLang as the CFML engine
* Enables URL rewrites (recommended for ColdBox applications)
* Uses OpenJDK 21 (required for BoxLang)
* Installs required compatibility modules on first server start

Start your server with:

```bash
box start
```

{% hint style="info" %}
The compatibility modules are only required for BoxLang applications. CFML applications using Adobe ColdFusion or Lucee don't need these additional modules.
{% endhint %}

## Asset Integration

CBWIRE requires CSS and JavaScript assets to function properly. By default, CBWIRE 4 automatically injects these assets into your application's layout, so no manual configuration is needed.

### Automatic Asset Injection (Default)

When automatic asset injection is enabled (default), CBWIRE will automatically include the necessary CSS in your page's `<head>` and JavaScript before the closing `</body>` tag. Your layout will automatically include content similar to this:

```html
<!doctype html>
<html>
<head>
    <!-- CBWIRE CSS (automatically injected) -->
    <style>[wire\:loading] { display: none; } /* ... more styles ... */</style>
</head>
<body>
    <!-- Your content -->
    
    <!-- CBWIRE JavaScript (automatically injected) -->
    <script src="/modules/cbwire/includes/js/livewire.js" data-csrf="..." data-update-uri="/cbwire/update"></script>
</body>
</html>
```

### Manual Asset Management

If you prefer to control when and how assets are loaded, you can disable automatic injection:

```javascript
// config/ColdBox.bx (BoxLang) or config/ColdBox.cfc (CFML)
moduleSettings = {
    "cbwire": {
        "autoInjectAssets": false
    }
};
```

Then manually include the assets in your layout:

{% tabs %}
{% tab title="BoxLang" %}

```html
<!-- layouts/Main.bxm -->
<bx:output>
<!DOCTYPE html>
<html>
    <head>
        <!-- CBWIRE CSS -->
        #wireStyles()#
    </head>
    <body>
        <!-- Your application content -->
        
        <!-- CBWIRE JavaScript -->
        #wireScripts()#
    </body>
</html>
</bx:output>
```

{% endtab %}

{% tab title="CFML" %}

```html
<!-- layouts/Main.cfm -->
<cfoutput>
<!DOCTYPE html>
<html>
    <head>
        <!-- CBWIRE CSS -->
        #wireStyles()#
    </head>
    <body>
        <!-- Your application content -->
        
        <!-- CBWIRE JavaScript -->
        #wireScripts()#
    </body>
</html>
</cfoutput>
```

{% endtab %}
{% endtabs %}

## Next Steps

Congratulations! You've successfully set up CBWIRE. Here are some recommended next steps:

* **Learn the Essentials**: Explore [Components](/cbwirev4/the-essentials/components), [Templates](/cbwirev4/the-essentials/templates), and [Data Binding](/cbwirev4/the-essentials/properties)
* **Explore Actions**: Understand how [Actions](/cbwirev4/the-essentials/actions) work and handle user interactions
* **Master Template Directives**: Learn about [wire:click](/cbwirev4/template-directives/wire-click), [wire:model](/cbwirev4/template-directives/wire-model), and other directives
* **Advanced Features**: Discover [Events](/cbwirev4/the-essentials/events), [File Uploads](/cbwirev4/features/file-uploads), and [Alpine.js Integration](https://github.com/ortus-docs/cbwire-docs/blob/v4.x/features/alpine-js.md)

## Troubleshooting

If you encounter issues:

1. **Verify assets are loaded**: Check your browser's developer tools to ensure CBWIRE CSS and JavaScript are present
2. **Check server logs**: Look for any CBWIRE-related errors in your application logs
3. **Validate requirements**: Ensure all system requirements are met, especially for BoxLang applications
4. **Review configuration**: Double-check your ColdBox configuration if using custom settings

{% hint style="warning" %}
CBWIRE requires its CSS and JavaScript assets to function. If components aren't responding to interactions, verify that assets are properly loaded in your browser's developer tools.
{% endhint %}

{% hint style="info" %}
Previous versions of CBWIRE required manual asset inclusion. CBWIRE 4 automatically handles this by default, making setup much simpler.
{% endhint %}




---

[Next Page](https://cbwire.ortusbooks.com/llms-full.txt/1)

