gpt4 book ai didi

ruby-on-rails - controller.js.coffee 中的函数

转载 作者:行者123 更新时间:2023-12-04 05:37:28 24 4
gpt4 key购买 nike

我在用 CoffeeScript 创建函数时遇到了一些麻烦,我想我错过了一些东西。对于我的用户 Controller ,我想为注册表单创建客户端验证。我想我错过了关于这一切如何运作的一些基本知识。

<%= form_for @user, :html => {:onsubmit => "return validate_signup_form();"} do |f| %>

CoffeeScript( Assets /users.js.coffee):
validate_signup_form = () ->
alert "Hi"
return false

预期输出:
var validate_signup_form;
validate_signup_form = function() {
alert("Hi");
return false;
};
validate_signup_form();

实际输出:
(function() {
var validate_signup_form;
validate_signup_form = function() {
alert("Hi");
return false;
};
}).call(this);

最佳答案

实际上,一切都按预期进行。如您所见 here , Coffeescript 将你的代码包装在一个匿名函数中,以防止对全局命名空间的污染。如果您只看一眼示例,您可能会错过这一点,但文档明确指出:

Although suppressed within this documentation for clarity, all CoffeeScript output is wrapped in an anonymous function: (function(){ ... })(); This safety wrapper, combined with the automatic generation of the var keyword, make it exceedingly difficult to pollute the global namespace by accident.



为了访问在此人工范围内声明的对象、变量或方法,您需要使其在全局范围内显式可用,例如像这样:
window.validate_signup_form = validate_signup_form

在您提到的情况下,我肯定会使用事件来触发该方法。

顺便说一句:方法声明中不需要空括号 foo =->工作得很好。

关于ruby-on-rails - controller.js.coffee 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6423499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com