access Stimulus JS from rails RJS

628 Views Asked by At

Is there a way how to access Stimulus JS controller action from Rails RJS view ?

e.g.:

//app/views/posts/create.js.erb`
$('#tags').hide();

I could do

//app/javascripts/controllers/my_stimuous_controller
import { Controller } from 'stimulus'
export default class extends Controller {

  hideElementAction(event) {
    //....
  }
}


//app/views/posts/create.js.erb`
myStimulousController.callAction('hideElementAction');

for those who don't know what RJS is: "ruby-to-js" template system in Ruby on Rails

1

There are 1 best solutions below

0
Breno Gazzola On

No. Instead, add the action to the element, and fire on it. Here's an example using hide as the event, but you can name it anything you like.

<div id="tags" 
     data-controller="my-stimulus-controller" 
     data-action="hide->my-stimulus-controller#hideElementAction">
</div>


Rails.fire(document.querySelector("#tags"), 'hide')