“Can't find variable” error with Rails 3.1 and Coffeescript

前端 未结 2 1708
伪装坚强ぢ
伪装坚强ぢ 2020-11-29 01:57

I have views in my application that reference my application.js file which contains functions I use throughout my application.

I just installed the Rails 3.1 release

相关标签:
2条回答
  • 2020-11-29 02:32

    By default, every CoffeeScript file is compiled down into a closure. You cannot interact with functions from a different file, unless you export them to a global variable. I'd recommend doing something like this:

    On top of every coffeescript file, add a line like

    window.Application ||= {}
    

    This will ensure that there's a global named Application present at all times.

    Now, for every function that you'll have the need to call from another file, define them as

    Application.indicator_tag = (el) ->
      ...
    

    and call them using

    Application.indicator_tag(params)
    
    0 讨论(0)
  • 2020-11-29 02:46

    Dogbert's solution is a great way to go if you have a very sophisticated JS back-end. However, there's a much simpler solution if you only have a handful of functions you're working with. Just add them directly to the window object, like this:

    window.indicator_tag = (el) ->
      ...
    

    Then you can use your functions from anywhere without having to wrap them up in another object.

    0 讨论(0)
提交回复
热议问题