Coffescript 如何访问其他资产的功能?
所以我有两个控制器,hotels
和 videos
。我希望 hotels.js.coffee
能够访问 videos.js.coffee
中创建的函数,但出现“未定义”错误。
我是 CoffeeScript 的新手,所以任何线索将不胜感激。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
CoffeeScript 会将你的咖啡编译为 JS,封装在一个自执行函数中,其作用域为窗口 (function{}).call(this);
因此,在videos.js.coffee中,您可以编写如下内容:
getVideo函数将绑定到window对象。
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:
and the getVideo function will be bound to the window object.
CoffeScript 在匿名函数内运行,因此在同一文件中声明的函数不会导出为全局函数。
尝试这样的方法来声明全局函数:
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:
在编译期间,CoffeeScript 将您的代码包装在匿名函数中并应用它。您必须以适合您的环境的预期方式导出公共接口。
然后,您需要在 Node.js 中使用
require()
并通过引用浏览器中的window
对象。在浏览器中还有其他方法可以执行此操作。查看 RequireJS。
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.
You then require using
require()
in node.js and by referencing thewindow
object in the browser.There are other ways to do this in the browser. Look into RequireJS.
事实上,您可以使用顶级窗口变量,或通过 CommonJS 提供的导出对象。请注意,您还可以授予对完整控制器的访问权限,而不仅仅是功能。
请参阅 http:// /jashkenas.github.com/coffee-script/。
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/.