最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to execute custom javascript functions in Rails 6 - Stack Overflow

programmeradmin2浏览0评论

With the arrival of Webpacker to Ruby On Rails, I can't find a way to use my JavaScript functions.

I have a file called app-globals.js with a function to test:

function alerts() {
  alert("TEST")
}

Then I want to use it in one of my views:

<% = button_tag 'Button', type: 'button', onClick: 'alerts ()'%>

But when I press the button, this error is shown in the browser console:

ReferenceError: alerts is not defined

  1. I placed the app-globals.js file in "app/javascript" and in "app/ javascript/packs/application.js" I placed require ("app-globals").

  2. I moved app-globals.js to "app/javascript/packs" and removed the require ("app-globals") from application.js.

With either case, an error still appears.

With the arrival of Webpacker to Ruby On Rails, I can't find a way to use my JavaScript functions.

I have a file called app-globals.js with a function to test:

function alerts() {
  alert("TEST")
}

Then I want to use it in one of my views:

<% = button_tag 'Button', type: 'button', onClick: 'alerts ()'%>

But when I press the button, this error is shown in the browser console:

ReferenceError: alerts is not defined

  1. I placed the app-globals.js file in "app/javascript" and in "app/ javascript/packs/application.js" I placed require ("app-globals").

  2. I moved app-globals.js to "app/javascript/packs" and removed the require ("app-globals") from application.js.

With either case, an error still appears.

Share Improve this question edited Jun 8, 2020 at 19:02 Syntle 5,1743 gold badges15 silver badges34 bronze badges asked Dec 15, 2019 at 23:50 Johan Donado B.Johan Donado B. 2853 silver badges14 bronze badges 1
  • Does this answer your question? Rails 5/6: How to include JS functions with webpacker? – Michael Chaney Commented Jun 8, 2020 at 16:57
Add a ment  | 

1 Answer 1

Reset to default 8

There is a workaround, though. You can:

change the function signatures from:

function myFunction() { ... }

to:

window.myFunction = function() { ... }

So in your code we can do like below :-

app/javascript/packs/app-globals.js

window.alerts = function() {
    alert ("TEST");
}

and then require this file to application.js :-

app/javascript/packs/application.js

require("@rails/ujs").start()
require("turbolinks").start()

require("@rails/activestorage").start()
require("channels")
require("jquery")

import $ from 'jquery'
window.jQuery = $;
window.$ = $;


require("packs/app-globals") ## require your file
发布评论

评论列表(0)

  1. 暂无评论