How can Coffescript access functions from other assets?

我与影子孤独终老i 提交于 2019-12-22 06:44:57

问题


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



来源:https://stackoverflow.com/questions/6163019/how-can-coffescript-access-functions-from-other-assets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!