controller.js.coffee 中的函数
我在使用 CoffeeScript 创建函数时遇到一些问题,我想我错过了一些东西。对于我的用户控制器,我想为注册表单创建客户端验证。我认为我错过了这一切如何运作的一些基本内容。
<%= 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);
I'm having some trouble creating functions with CoffeeScript, I guess I've missed something. For my users controller I'd like to create client-side validation for a signup form. I think I've missed something fundamental with how this all works.
<%= form_for @user, :html => {:onsubmit => "return validate_signup_form();"} do |f| %>
CoffeeScript (assets/users.js.coffee):
validate_signup_form = () ->
alert "Hi"
return false
Expected output:
var validate_signup_form;
validate_signup_form = function() {
alert("Hi");
return false;
};
validate_signup_form();
Real output:
(function() {
var validate_signup_form;
validate_signup_form = function() {
alert("Hi");
return false;
};
}).call(this);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事实上,一切都按照预期进行。正如您可以在此处阅读的那样,Coffeescript 将您的代码包装在匿名函数中以防止污染全局命名空间。如果您只看一下示例,您可能会错过这一点,但文档明确指出:
为了访问在此人工范围内声明的对象、变量或方法,您需要使其在全局范围内显式可用,例如:
在您提到的情况下,我肯定会使用事件来触发方法。
顺便说一句:方法声明中不需要空括号
foo =->
就可以正常工作。Actually everything works just as it's supposed to. As you can read here, Coffeescript wraps your code in an anonymous function to prevent the pollution of the global namespace. If you just glance at the examples, you might miss this, but the docs clearly state:
In order to access an object, variable or method declared within this artificial scope, you'll need to make it explicitly available within the global scope, e.g. like this:
In the case you're mentioning I'd definitely use events to trigger the method.
Btw.: No need for the empty parenthesis in your method declaration
foo =->
works just fine.Polarblau的回答是非常正确的。另请参阅:
闭包包装器是保持文件模块化的好方法(因为它们应该如此),所以我强烈建议不要删除它。请注意,在模块的外部范围中,
this
/@
将是window
,因此您可以使代码按预期工作只需添加一个字符:您可以选择使用
@
还是window.
来定义全局变量,但使用@
样式还有另一个优点:如果您在 Node.js 应用程序中重用代码,那么它仍然有效。这些对象将附加到exports
而不是window
。polarblau's answer is quite correct. See also:
The closure wrapper is a great way of keeping files modular (as they should be), so I strongly advise against getting rid of it. Note that in the outer scope of your modules,
this
/@
is going to bewindow
, so you can make your code work as intended by just adding a single character:It's up to you whether you'd prefer to use
@
orwindow.
for defining globals, but the@
style has another advantage: If you reuse your code in a Node.js application, then it'll still work. Those objects will be attached toexports
instead ofwindow
.