Call javascript functions from html in rails 3.1

Using coffeescript, jQuery and asterisks in rails 3.1, coffeescript files are compiled into blocks, such as:

(function() { var a; var b; var c; foo = function() { alert("foo"); } bar = function() { alert("bar"); } }).call(this); 

This seems to move the foo and bar functions out of the global scope, so bar can be called foo, but none of them can be called from html code. When I try to call foo from the select onchange element, I get "Can't find variable: foo".

The workaround right now is to move all globally available functions to .js files. But what is the right way to do this?

thanks

+2
source share
1 answer

I prefer to declare a top-level object (for the namespace) and attach to it all the functions that I need access to.

At the top of the file add something like

 window.App = window.App || {}; 

Then declare your functions

 var foo = function() { ... }; var bar = function() { ... }; 

Finally, export functions are needed

 window.App.foo = foo; 

A bit related information - โ€œUnable to find variableโ€ error with Rails 3.1 and Coffeescript

+4
source

All Articles