It's very common in Stimulus.js
to call the .preventDefault()
or .stopPropagation()
methods on an Event
object immediately after a controller's action has been fired:
import { Controller } from "@hotwired/stimulus";
export default class extends Controller {
open(event) {
event.preventDefault();
/* ... action logic ... */
}
close(event) {
event.stopPropagation();
/* ... action logic ... */
}
}
But it starts to feel repetitive after a while; which is why a PR introduced by yours truly to the hotwired/stimulus repo makes it so that you can do those things while defining the action descriptors themselves:
<div data-controller="modal">
<a data-action="modal#open:prevent">Open</a>
<!-- ... modal body ... -->
<span data-action="click->modal#close:stop">Close</span>
</form>
As you can see, we have two new Event Modifiers, :prevent
and :stop
. The former calls .preventDefault()
, and the latter calls .stopPropagation()
on the event before calling the controller action.
You can even chain these modifiers (which isn't something this PR introduced):
<div data-controller="clipboard" data-action="click->clipboard#copy:prevent:stop">
Copies this text!
</form>
Disclaimer
At the time of writing this blog, this feature isn't available in any release. Please use the main
branch of the hotwired/stimulus repo if you want to play with it.