Functions in the .js.coffee Controller

I had problems creating functions with CoffeeScript, I probably missed something. For my user controller, I would like to create a client-side check for the registration form. I think I missed something fundamental in how it 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 Result:

 var validate_signup_form; validate_signup_form = function() { alert("Hi"); return false; }; validate_signup_form(); 

The real conclusion:

 (function() { var validate_signup_form; validate_signup_form = function() { alert("Hi"); return false; }; }).call(this); 
+4
source share
2 answers

In fact, everything works as intended. As you can read here , Coffeescript wraps your code with an anonymous function to prevent pollution of the global namespace. If you just look at the examples, you can skip this, but the docs clearly state:

Although suppressed in this documentation for clarity, all CoffeeScript Outputs are wrapped in an anonymous function: (function () {...}) (); This protective shell, combined with the automatic generation of the var keyword, makes it extremely difficult to contaminate the global namespace by accident.

In order to access an object, variable or method declared in this artificial scope, you will need to make this explicitly available in the global scope, for example. eg:

 window.validate_signup_form = validate_signup_form 

In the case you mention, I would definitely use events to trigger the method.

Btw: There is no need for an empty bracket in the declaration of your method foo =-> works fine.

+6
source

the polar answer is quite correct. See also:

A wrapper for closing is a great way to keep files modular (as it should be), so I highly recommend getting rid of it. Note that in the outer area of โ€‹โ€‹your modules this / @ will have a window , so you can get your code to work as intended by simply adding one character:

 @validate_signup_form = -> alert "Hi" false 

It depends on whether you want to use @ or window. to define global variables, but the @ style has another advantage: if you reuse your code in a Node.js application, then it will still work. These objects will be bound to exports instead of window .

+3
source

All Articles