Stimulus Discourse

Possible to stop calls with multiple actions?


#1

If you’re using multiple actions in an element, is it possible to stop/abort the chain in some way?

<input type="text" data-action="focus->formatter#verify keydown->form#submit">

So if verify() failed I’d want to stop submit() from being called at all. Note these are in two different controllers.

My particular scenario is that I’ve got a generic controller that is on all “Cancel” buttons in forms throughout my site. But for some forms I have a controller specific to handling fields on that form, including possibly the “Cancel” button to override behavior. So if the form-specific controller redefines what Cancel should do I don’t want it to continue to the generic “Cancel” handler, which just closes the form.

I’m currently handling this through inheritance: the custom controllers inherit from the generic controller so if cancel() is overridden everything works. But this requires that I have that custom Stimulus controller in place for every form, even if I don’t need to override the cancel behavior. So I want to always include the generic cancel handler and if a form-specific Stimulus controller exists, that function should be called first:

<a href="#" data-action="click-><%= stimulus_controller_name %>#cancel click->forms#cancel">Cancel</a>

This code always inserts the name of a stimulus controller that corresponds to the same rails controller, however there may not actually be an actual file (no form-specific JS for this page). In that case Stimulus ignores the first action and calls the second one.

If the Stimulus controller DOES exist, that method gets called and then the generic one gets called always. I want to cancel the generic one from running, if possible.


#2

Yes! The DOM method you’re looking for is Event#stopImmediatePropagation(). We added support for this in Stimulus 1.1 (#149).


#3

AWESOME!! I tried Event#stopPropagation() but forgot about Immediate! Thanks Sam!


#4

I created a PR that adds a line of documentation to the Reference manual: https://github.com/stimulusjs/stimulus/pull/223