This is a supercharged Stimulus Controller. You can extend all of your Stimulus controllers from this one and access a few handy functions everywhere.
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 |
Composing
import { Controller } from '@hotwired/stimulus'
import { useApplication } from 'stimulus-use'
export default class extends Controller {
connect() {
useApplication(this)
}
}
Extending a controller
// greet_controller.js
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.github.io/stimulus-use/#/use-dispatch?id=migration-guide
}
}
!> 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
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
//item_controller.js
import { ApplicationController } from 'stimulus-use'
export default class extends ApplicationController {
add() {
this.dispatch('add', { quantity: 1 })
}
}
The cart controller receiving the event
//cart_controller.js
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'))
}
}