How to execute custom javascript functions in Rails 6

后端 未结 1 1201
庸人自扰
庸人自扰 2021-01-12 12:02

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

1条回答
  •  礼貌的吻别
    2021-01-12 12:25

    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 讨论(0)
提交回复
热议问题