useApplication
This is a supercharged Stimulus Controller. You can extend all of your Stimulus controllers from this one and access a few handy functions everywhere.
Reference
useApplication(controller, options = {})controller: A Stimulus Controller (usually 'this')
options:
| Option | Description | Default value |
|---|---|---|
overwriteDispatch | Whether to call the deprecated useDispatch() on the controller or not. | true |
When overwriteDispatch is true, the whole options object is passed through to useDispatch, so it also accepts all of its options: element, eventPrefix, bubbles, cancelable and debug. See useDispatch for their descriptions and default values.
Usage
Composing
import { Controller } from '@hotwired/stimulus'
import { useApplication } from 'stimulus-use'
export default class extends Controller {
connect() {
useApplication(this)
}
}Extending a controller
import { ApplicationController } from 'stimulus-use'
export default class extends ApplicationController {
connect() {
this.isPreview // true/false if it is a Turbolinks preview
this.isConnected // true/false if the controller is connected
this.dispatch("hello") // helper to dispatch a custom event "greet:hello" to other Stimulus controllers
// this.dispatch() is deprecated: For more information https://stimulus-use.dev/use-dispatch#migration-guide
}
}Functions
WARNING
Deprecated: dispatch(name, eventArgs): helper function to dispatch events to other Stimulus controllers
metaValue(name): return the value of a meta attribute
Getters
isPreview: returns true/false whether the current page is a Turbo/Turbolinks preview. Use case for playing animations with Turbolinks
isConnected: returns true/false for whether the Stimulus controller is connected or not.
csrfToken: return the CSRF token if any
Example building a cart counter with the dispatch helper
The HTML markup. See the custom event item:add that the cart controller is listening to
<div
data-controller="cart"
data-action="item:add->cart#refreshTotal"
data-cart-counter="0"
>
<button data-controller="item" data-action="item#add">
Add
</button>
<div>
<span>No of items:</span>
<span data-cart-target="counterView">0</span>
</div>
</div>The item controller dispatching the event
import { ApplicationController } from 'stimulus-use'
export default class extends ApplicationController {
add() {
this.dispatch('add', { quantity: 1 })
}
}The cart controller receiving the event
import { ApplicationController } from 'stimulus-use'
export default class extends ApplicationController {
static targets = ['counterView']
refreshTotal(e) {
this.counter += e.detail.quantity
console.log(e.detail.controller) // the emitting item_controller
}
renderCounter() {
this.counterViewTarget.textContent = this.counter
}
set counter(value) {
this.data.set('counter', value)
this.renderCounter()
}
get counter() {
return parseInt(this.data.get('counter'))
}
}