1

In my Rails project, in which I am using Coffeescript, I want to be able to do something like this in a view:

f.text_area :content, :size => "77x4", :oninput => 'Helpers.expandTextarea(300)'

This would call a coffeescript function that would expand the textarea when required. My problem is that I can't seem to properly namespace the coffeescript to get this to work. I tried to do it like this

# site.js.coffee
Helpers =
  expandTextarea: ->
    alert "function found!"

This doesn't work. Trying to call Helpers in the browser console will throw an undefined error. My question is this:

What code would I use in site.js.coffee to achieve the namespacing I want?

1 Answer 1

2

You could manually put Helpers into the global namespace:

window.Helpers =
  expandTextarea: ->
    alert "function found!"

Then you should be able to say Helpers.expandTextarea(300) anywhere you want. Assuming, of course, that site.js.coffee is included on every page.

CoffeeScript files are wrapped in functions by default:

(function() { /* compiled CoffeeScript goes here */ })();

to avoid polluting the global namespace. You can supply options to the CoffeeScript compiler to not wrap like this but you're better off explicitly putting global things into window.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.