0

I'm a js noob working on a Rails app. I defined a useful JS function in one of my javascript files, and I'd like it to be available to call in other files. However, it's not. Here's a simplified example of my situation... note that I'm using CoffeeScript (but AFAIK that should make no difference):

#file: app/assets/javascripts/foos.js.coffee
testFoo: ->
  alert 'Foo'

#file: app/assets/javascripts/bars.js.coffee
jQuery ->
  testFoo()

This doesn't work, and in the console I get: testFoo is not defined.

Both files are included in the page, if I put an alert or console log in either one the page responds as expected. I feel like I must be overlooking something brutally obvious here... what is it?

Andrew
  • 42,517
  • 51
  • 181
  • 281
  • When you say "both are included on the page" do you mean you have two script elements in your HTML? If so check the ordering and the spelling, etc. – Ray Toal Apr 21 '12 at 04:39
  • 1
    possible duplicate of [CoffeeScript & Global Variables](http://stackoverflow.com/questions/4214731/coffeescript-global-variables) – Matt Ball Apr 21 '12 at 04:40
  • 1
    @RayToal: CoffeeScript wraps everything in `(function() { ... })()` wrappers to prevent polluting the global namespace. – mu is too short Apr 21 '12 at 04:42
  • See the following Thread: http://stackoverflow.com/questions/4214731/coffeescript-global-variables – Mostafa Ali Apr 21 '12 at 04:56

1 Answers1

2

In short try this :

root = exports ? this
root.foo = -> alert 'Foo'
Mostafa Ali
  • 151
  • 4