2

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 %>
Mark Boulder
  • 13,577
  • 12
  • 48
  • 78
  • your function is inside on change event of pagecontainershow so i don't think it'll like this. you would have to call either your page change or need to separate it out from that block – Mandeep Jul 08 '14 at 18:15

3 Answers3

0

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

Joseph N.
  • 2,437
  • 1
  • 25
  • 31
  • this wont solve the issue here as you are calling create method and that time all the js files are already loaded in your page so there order wont matter – Mandeep Jul 08 '14 at 18:13
0

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 %>
Mandeep
  • 9,093
  • 2
  • 26
  • 36
0

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

global jquery function

Community
  • 1
  • 1
Mark Boulder
  • 13,577
  • 12
  • 48
  • 78
  • 1
    You should generally avoid using global variables and functions, specially when you can do it more normal way. Check out http://stackoverflow.com/questions/2613310/ive-heard-global-variables-are-bad-what-alternative-solution-should-i-use or https://gist.github.com/hallettj/64478 – Mandeep Jul 11 '14 at 17:12