calling javascript functions from html in rails 3.1
Using coffeescript, jQuery, and sprockets in rails 3.1 the coffeescript files are compiled in to blocks like:
(function() {
var a;
var b;
var c;
foo = function() {
alert("foo");
}
bar = function() {
alert("bar");
}
}).call(this);
This seems to move functions foo and bar out of global scope, so bar can be called by foo, but neither can be called from the html code. When I try to call foo from a select onchange ele开发者_如何学运维ment, I get a "Can't find variable: foo".
The workaround right now is to move all globally available functions to .js files. But what's the right way to do this?
Thanks
I prefer declaring a top level object (for namespacing), and attaching all the functions that I'll need access to, to it.
At the top of your file, add something like
window.App = window.App || {};
Then declare your functions
var foo = function() { ... };
var bar = function() { ... };
Lastly, export functions needed
window.App.foo = foo;
Somewhat related info - "Can't find variable" error with Rails 3.1 and Coffeescript
精彩评论