Hotwire Discussion

New Stimulus package: Stimulus Invoke

Hi folks,

I’ll like to introduce to you a new Stimulus package: Stimulus Invoke!

The main goal of this package is to fill the gap between Hotwire Turbo Frames/Streams responses and Stimulus controllers to replace Rails UJS.

It allows to invoke any Stimulus actions of any Stimulus controllers, anywhere in the DOM, automatically with the help of a Custom Element <stimulus-invoke>.

This package should be use in last resort. Basically when you need to interact with advanced/complex Stimulus controllers.
Here some use cases:

  • Hide a modal when rendering a Turbo Stream response:
    <turbo-stream target="user_modal_1" action="append">
      <template>
        <stimulus-invoke action="modal#hide"></stimulus-invoke>
      </template>
    </turbo-stream>
    
  • Call a checkbox-list#checkboxAdded Stimulus action when a new checkbox (who is a target of a the checkbox-list Stimulus controller) is added by a Turbo Stream response:
    <turbo-stream target="users_table_body" action="append">
      <template>
        <tr id="user_2">
          <td>
            <input type="checkbox" name="ids[]" value="2" data-checkbox-list-target="checkbox">
            User 2
          </td>
        </tr>
    
        <stimulus-invoke
          action="checkbox-list#checkboxAdded"
          source="#user_2 [data-checkbox-list-target~=checkbox]"
        ></stimulus-invoke>
      </template>
    </turbo-stream>
    

Behind the scene no magics :dizzy:, it encapsulates a Stimulus controller who can interact with others Stimulus controllers.

More info here: efficiently / stimulus-invoke · GitLab

And if you want to run some examples, you can follow these instructions: Running Stimulus Invoke examples
Or directly read the source code of these examples, here

Have a good day,
Tortue Torche

4 Likes