> For the complete documentation index, see [llms.txt](https://shinyobjectlabs.gitbook.io/framework-js/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://shinyobjectlabs.gitbook.io/framework-js/javascript-api/custom-functions.md).

# Custom Functions

### Overview

Custom functions are written like any normal JavaScript function. A components reactive store can be accessed via the [API](https://shinyobjectlabs.gitbook.io/framework-js/javascript-api/reactive-store.md) or [Magic Refs](#magic-refs).\
\
We recommend the use of custom functions wherever possible to minimise complex logic creeping into attributes.

### Example

#### ❌ Not Recommended

```markup
<span x-text="first_name + ' ' + last_name"></span>
```

Whilst this is convenient, it becomes significantly more challenging to maintain.

#### ✅ Recommended

```markup
<span x-text="fullName($store)"></span>
```

In this example, we utilise the magic references available in attribute expressions.

```javascript
function fullName(store) {
 return store.first_name + ' ' + store.last_name;
 // or return `${store.first_name} ${store.last_name}`;
}
```

### Magic Refs

<table><thead><tr><th width="175">Name</th><th width="450">Description</th><th>Optional</th></tr></thead><tbody><tr><td>$store</td><td>Reference to the components reactive store</td><td>✅</td></tr><tr><td>$el</td><td>Reference to the DOM element bound to the directive</td><td>✅</td></tr><tr><td>$event</td><td>Reference to the <code>Event</code> emitted from the user action</td><td>✅</td></tr></tbody></table>

### Example

Here's the `submitForm()` function used in the `x-on:submit` example.

```html
<form x-on:submit="submitForm($store, $event)">
    <input x-model="fields.first_name">
    <input x-model="fields.last_name">
</form>
```

```javascript
function submitForm(store, evt) {
    evt.preventDefault();
    
    // reset the state
    store.displaySuccess = false;
    store.displayError = false;
    
    // log the fields data
    console.log(store.fields);
    
    //update the state to display the success message
    store.displaySuccess = true;
}
```
