Stopping a click event without breaking your turbostream

In a Rails application I have a link that has various elements within it. Some of those elements are actionable on their own while others are such that I want them to open the parent link when clicked. The elements that are actionable should not open the parent link when clicked. The link, among other things, renders a turbostream.

But clicking on the check box will also open the link to the edit task path. Bad. This happens because a click event bubbles or propagates up to the parents of the element on which the click occurs. So, we need to stop that propagation.

Helpfully, stimulus provides an option that can be appended to actions that will prevent those actions from propagating: the :stop option (for .stopPropagation()).

We click on our check box and…the link is still opened but now the turbostream that the link was supposed to render is broken. Something in the way that turbostream works involves an event that needs to propagate to work. That in and of itself shouldn’t be an issue since we only care about what turbostream is doing if the link is opened and the link shouldn’t be opening. Why is the link opening?

Because there are actually two different events firing when I click the check box: a click event and a link click event. The important thing to know about these events is that the click event, but not the link click event, doesn’t bubble up if the :stop option is appended to the stimulus action. To stop the link click event, you also need to append the :prevent (for .preventDefault()) to the action.

Now when I click on the check box, the select method from the selectable-table stimulus controller fires but the link does not open. Success!

You can read more about the difference between .stopPropagation() and .preventDefault() here.


Leave a comment