Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Rails-UJS in JS modules (Rails 6 with webpacker)

i just switched to Rails 6 (6.0.0.rc1) which uses the Webpacker gem by default for Javascript assets together with Rails-UJS. I want to use Rails UJS in some of my modules in order to submit forms from a function with:

const form = document.querySelector("form") Rails.fire(form, "submit") 

In former Rails versions with Webpacker installed, the Rails reference seemed to be "globally" available in my modules, but now i get this when calling Rails.fire

ReferenceError: Rails is not defined 

How can i make Rails from @rails/ujs available to a specific or to all of my modules?

Below my setup…

app/javascript/controllers/form_controller.js

import { Controller } from "stimulus"  export default class extends Controller {   // ...   submit() {     const form = this.element     Rails.fire(form, "submit")   }   // ... } 

app/javascript/controllers.js

// Load all the controllers within this directory and all subdirectories.  // Controller files must be named *_controller.js.  import { Application } from "stimulus" import { definitionsFromContext } from "stimulus/webpack-helpers"  const application = Application.start() const context = require.context("controllers", true, /_controller\.js$/) application.load(definitionsFromContext(context)) 

app/javascript/packs/application.js

require("@rails/ujs").start() import "controllers" 

Thanks!

like image 786
R4ttlesnake Avatar asked May 14 '19 10:05

R4ttlesnake


People also ask

Does rails 7 Use Webpacker?

Taking into consideration all the major shifts in modern Javascript development, Rails 7 has decided to replace Webpacker with importmapped Hotwire as default the JavaScript setup. This means that a default Rails skeleton will not have to require the full JavaScript toolchain with Webpack by default.

Do I need rails Ujs?

you only need require rails_ujs , otherwise if you are doing any type of submission from client (for example), an alert will process twice.

What does Webpacker do in Rails?

With webpack, you can manage JavaScript, CSS, and static assets like images or fonts. Webpack will allow you to write your code, reference other code in your application, transform your code, and combine your code into easily downloadable packs.

What is Rails UJS for?

Rails UJS (Unobtrusive JavaScript) is the JavaScript library that helps Rails do its magic when we use options like remote: true for many of the html helpers. In this article I'll try to explain the main concept of how this works to make it transparent for the user.


1 Answers

in my app/javascript/packs/application.js:

import Rails from '@rails/ujs'; Rails.start(); 

and then in whatever module, controller, component I'm writing:

import Rails from '@rails/ujs'; 
like image 172
inopinatus Avatar answered Sep 17 '22 15:09

inopinatus