在rails 3.1中从html调用javascript函数 [英] calling javascript functions from html in rails 3.1

查看:142
本文介绍了在rails 3.1中从html调用javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在rails 3.1中使用coffeescript,jQuery和sprockets,coffeescript文件被编译到如下块:

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);

这似乎将函数foo和bar移出全局范围,所以bar可以通过foo,但两者都不能从html代码调用。当我尝试从select onchange元素调用foo时,我得到一个找不到变量:foo。

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".

现在的解决方法是移动所有全局可用函数.js文件。

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

感谢

推荐答案

我喜欢声明一个顶级对象(用于命名空间),并将所有需要访问的函数附加到它。

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 || {};

然后声明您的函数

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

最后,需要导出函数

window.App.foo = foo;

有些相关资讯 - 找不到变量 Rails 3.1和Coffeescript 出现错误

Somewhat related info - "Can't find variable" error with Rails 3.1 and Coffeescript

这篇关于在rails 3.1中从html调用javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆