calling javascript functions from html in rails 3.1

淺唱寂寞╮ 提交于 2019-12-11 02:24:11

问题


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 element, 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


回答1:


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



来源:https://stackoverflow.com/questions/6685292/calling-javascript-functions-from-html-in-rails-3-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!