javascript 调用用咖啡脚本定义的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10458891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:56:46  来源:igfitidea点击:

Calling functions defined with coffee script?

javascripthtmlcoffeescript

提问by rudolph9

I have the following coffeescript code to generate and alert box:

我有以下咖啡脚本代码来生成和警报框:

show_alert = () ->
  alert("Hello! I am an alert box!")

which compiles to:

编译为:

(function() {
  var show_alert;

  show_alert = function() {
    return alert("Hello! I am an alert box!");
  };

}).call(this);

in my html I have the following

在我的 html 中,我有以下内容

<input onclick='show_alert()' type='button' value='Show alert box' />

However, no alert box shows? The following is the html copied from the browser:

但是,没有警告框显示?以下是从浏览器复制的html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>Test Rails Application</title>
    <style type='text/css'>.application h1 {
  color: lime; }
</style>
    <script type='text/javascript'>(function() {
  var show_alert;

  show_alert = function() {
    return alert("Hello! I am an alert box!");
  };

}).call(this);
</script>
  </head>
  <body>
    <h1>Hello from applicaiton.html.haml</h1>
    <div class='application'><h1>Hello World</h1>
<input onclick='show_alert()' type='button' value='Show alert box' />
</div>
  </body>
</html>

Why am I not able to get an alert box to show up?

为什么我无法显示警报框?

回答by Ulrich Dangel

Your problem is that the generated javascript code is in another scope. You have to solve this by either adding the -bparameter to the coffeescript compiler or export your function explicitly via

您的问题是生成的 javascript 代码在另一个范围内。您必须通过将-b参数添加到 coffeescript 编译器或通过显式导出您的函数来解决此问题

root = exports ? this
root.show_alert = () -> alert("Hello! I am an alert box!")

For more information about the exporting and scope issue have a look at https://stackoverflow.com/a/4215132/832273

有关导出和范围问题的更多信息,查看https://stackoverflow.com/a/4215132/832273

I created a working jsfiddlewith the above coffeescript code

我用上面的咖啡脚本代码创建了一个有效的 jsfiddle

回答by kapellan

I found two ways to solve this issue FIRST add @ before function name

我找到了两种方法来解决这个问题首先在函数名前添加@

@say_hi = () ->
  $(alert('Hello!!!'))

SECOND at the end of coffee file add

SECOND 在咖啡文件末尾添加

window["say_hi"] = say_hi

回答by akonsu

in your coffeescrpt code, try to save the function to window: window["show_alert"] = show_alert

在您的 coffeescrpt 代码中,尝试将函数保存到窗口:window["show_alert"] = show_alert