How can Coffescript access functions from other as

2019-05-01 14:54发布

问题:

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.

回答1:

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.



回答2:

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


回答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.



回答4:

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/.