开发者

Functions in controller.js.coffee

开发者 https://www.devze.com 2023-03-14 04:05 出处:网络
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 misse

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


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:

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.: No need for the empty parenthesis in your method declaration foo =-> works just fine.


polarblau's answer is quite correct. See also:

  • Getting rid of CoffeeScript's closure wrapper
  • How can I use option "--bare" in Rails 3.1 for CoffeeScript?

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 be window, so you can make your code work as intended by just adding a single character:

@validate_signup_form = ->
  alert "Hi"
  false

It's up to you whether you'd prefer to use @ or window. 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 to exports instead of window.

0

精彩评论

暂无评论...
验证码 换一张
取 消