5

So I have two controllers, hotels and videos. I want the hotels.js.coffee to be able to access functions created in videos.js.coffee but I get a "is not defined" error.

I'm new to CoffeeScript so any clues would be appreciated.

ivkremer
  • 1,234
  • 3
  • 23
  • 42
cbmeeks
  • 11,248
  • 22
  • 85
  • 136
  • There have been several recent questions along these lines. See http://stackoverflow.com/questions/6099342/how-can-i-use-option-bare-in-rails-3-1-for-coffeescript/6099872 and http://stackoverflow.com/questions/6137733/how-do-you-limit-coffeescript-or-javascript-execution-to-a-particular-controlle – Trevor Burnham May 28 '11 at 17:09

4 Answers4

14

CoffeeScript will compile your coffee to JS wrapped in a self-executing function with the scope of the window (function{}).call(this);

So in videos.js.coffee you can write something like:

    @getVideo: (id) ->

and the getVideo function will be bound to the window object.

Thurloat
  • 364
  • 1
  • 4
  • When I try this in a similar situation, I get a javascript error: missing : after property id [Break On This Error] this.hide_modal: function(modal_id) { My Function: `@hide_modal: (modal_id) -> animate_top = Number($('#' + modal_id).height() + 70) current_top = $('#' + modal_id).css('top') $('#' + modal_id).animate top: '-' + animate_top + 'px' 500 -> $(this).css({'top' : current_top, 'visibility': 'hidden'}); $('.reveal-modal-bg').fadeOut()` – David Savage Nov 04 '11 at 05:03
  • Sorry: http://pastebin.com/z9jFwfXp I've since moved on and used the same code, just replaced the @hide_modal with window.hide_modal – David Savage Nov 08 '11 at 01:17
8

CoffeScript runs inside an anonymous function, so declared funcitons in the same file, aren't exported as global functions.

Try something like this to declare global functions:

window.myFunction = ->
    //some code
erickzetta
  • 681
  • 5
  • 3
3

During compilation, CoffeeScript wraps your code in an anonymous function and applies it. You have to export your public interface in the expected manner for your environment.

(exports || window).publicMethod = (foo, bar) -> foo + bar

You then require using require() in node.js and by referencing the window object in the browser.

There are other ways to do this in the browser. Look into RequireJS.

lawnsea
  • 6,463
  • 1
  • 24
  • 19
0

Indeed you can use either the top-level window variable, or the exports object provide through CommonJS. Please note, you can also give access to complete controllers instead of just functions.

See the sections 'Lexical Scoping and Variable Safety' and '"text/coffeescript" Script Tags' at http://jashkenas.github.com/coffee-script/.

martijndeh
  • 361
  • 3
  • 11