2

I created a small custom javascript file with a function definition in app/assets/javascripts/custom.js

round_number = function(num, dec) {
  return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
};

The application works fine because the file is inserted in the asset pipeline. Then, for learning purpose, I converted it to coffescript:

round_number = (num, dec) ->
  Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec)

But with my surprise the application didn't work. I checked in localhost:3000/assets/custom.js that the coffescript was translated to:

(function() {
  var round_number;

  round_number = function(num, dec) {
    return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
  };

}).call(this);

Why the extra wrapping, that made the function unavailable where I need it?

If I insert the coffescript function not in custom.js.coffee file, but in app/assets/javascripts/orders.js.coffee (where Order is my class) it is translated in the expected javascript.

I wanted to put the shared javascript function in a separate file because it is more orderly. I know that, even if I put the function in orders.js.coffee it will be available in the whole application (that is what I want to accomplish), but I'm puzzled. Is there a best practice that I am missing here?

--- EDIT ---

I understood from "Can't find variable" error with Rails 3.1 and Coffeescript

I think that I will organize my Rails applications in this way:

1) Create a file app/assets/javascripts/global.js.coffee to contain all global variables and functions. In this file put a line

window.Global ||= {}

to define a namespace Global. Define the functions as

Global.function_name = (arguments) ->
  ...

2) Call the functions with:

Global.function_name(arguments)
Community
  • 1
  • 1
alcafar
  • 53
  • 1
  • 6

1 Answers1

0

Yes, if you want something available globally, set it as a property on the window. Coffeescript compiler wraps your code in an anonymous function to prevent accidental name clashing.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367