controller.js.coffee中的函数 [英] Functions in controller.js.coffee

查看:156
本文介绍了controller.js.coffee中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用CoffeeScript创建函数时遇到了一些麻烦,我想我错过了一些东西。对于我的用户控制器,我想为注册表单创建客户端验证。

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

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


推荐答案

实际上一切都如预期的那样工作。您可以在此处阅读,Coffeescript将代码封装在匿名函数中,以防止对全局命名空间造成污染。如果你只是看一下例子,你可能会错过这个,但文档清楚地说明:

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:


虽然在这个
文档为清楚起见,所有
CoffeeScript输出包装在
匿名函数中:(function(){...
})();这个安全包装器结合
与自动生成
var关键字,使得极大地使
难以偶然地污染全局
命名空间。

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.

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

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:

window.validate_signup_form = validate_signup_form

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

In the case you're mentioning I'd definitely use events to trigger the method.

Btw .:不需要你的方法声明中的空圆括号 foo = - > 很好。

Btw.: No need for the empty parenthesis in your method declaration foo =-> works just fine.

这篇关于controller.js.coffee中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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