简体   繁体   中英

Rails: Running a function from `application.js` inside a `.js.erb` file

How does one run a function from application.js inside a .js.erb file? I'd rather not have to duplicate said function.

app/assets/javascripts/application.js

$(document).on('pagecontainershow', function() {
  var someFunction = function() {
    function someOtherFunction() {
      console.log('Hello world')
    }
  }();
});

app/views/articles/create.js.erb

<% unless @article.errors.any? %>
  someFunction.someOtherFunction();
<% end %>

There is a comment in the default application.js created by rails which says

// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.

The way I could handle this is move your code to another js file say functions.js then take note of the order of how you reference them in application.js . Your functions.js should be required first before any other files using the functions. In your case, you could have something like

application.js

//= require jquery
//= require jquery_ujs
//= require functions
//= require_tree .

You should now be able to call that function inside create.js.erb

As i mentioned in my comment you either need to separate out your functions or you need to call the on change event which contains these functions . Try this:

function someotherfunction(){
  console.log("Hello");
}    

function somefunction(){
  someotherfunction();
  // your logic 
}

$(document).on('pagecontainershow', function(){
  somefunction();
});

<% unless @article.errors.any? %>
  someFunction();
<% end %>

I ended up making the function a global jQuery function and now it works great:

global jquery function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM