Stimulus: Stop event chain in the middle of multiple actions

kinopyo avatar

kinopyo

Stimulus supports multiple actions on a single element. For example, you can have a link like this:

<a href="#" data-action="session#requireLogin comment#toggleCommentForm">Comment</a>

When the link is clicked, it'll go through session_controller.js first to check whether the user is logged in, and if so, continue to comment_controller to show comment form.
But if the user is not logged in, we want to stop the event chain and show a login modal.

The key is event.stopImmediatePropagation(), available since Stimulus v1.1.

...[Stimulus] respect the ordering of action descriptors in data-action attributes, guaranteeing that actions are invoked from left to right, and that an action on the left can stop an event to prevent invocation of actions on the right.
https://github.com/stimulusjs/stimulus/pull/149

Sharing our session_controller to give you a full picture:

import { Controller } from "stimulus"

export default class extends Controller {
  requireLogin(event) {
    if (App.currentUser) return

    event.stopImmediatePropagation()
    event.preventDefault()

    this.loadLoginModal()
  }
}

That's it ⭐️ !

References:


I really like Stimulus - the light weight JavaScript framework and its modest / humble ambitions. It's simple; you can learn in 15 minutes. It's powerful; providing right amount of structures and conventions. I'm satisfied with my one-year experience with it. It's a great extraction.

I haven't written any tips for yet, mainly because I think it's so straightforward, the official Handbook and References have already covered everything. This post is more of an elaboration of an interesting use case I bumped into lately. 😺

kinopyo avatar
Written By

kinopyo

Indoor enthusiast, web developer, and former hardcore RTS gamer. #parenting
Published in Rails
Enjoyed the post?

Clap to support the author, help others find it, and make your opinion count.