构建咖啡脚本代码? [英] Structuring coffeescript code?

查看:22
本文介绍了构建咖啡脚本代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rails 3.1 下,我试图找出如何将一些咖啡脚本类从我的控制器默认咖啡脚本文件 (home.js.coffee) 移到另一个文件中,以便构建整体一点点.

Under Rails 3.1, I'm trying to find out how to move a few coffeescript classes away from my controller default coffeescript file (home.js.coffee) into another file, in order to structure the whole a little bit.

有谁知道如何将一个 coffeescript 文件包含"到另一个文件中?

Does anyone know how to "include" a coffeescript file into another?

推荐答案

您想要做的是导出功能.例如,如果您以

What you want to do is export functionality. For instance, if you start with

class Foo
  ...

class Bar extends Foo
  ...

并且您决定将 Foo 移动到它自己的文件中,该文件应该看起来像

and you decide you move Foo to its own file, that file should look like

class Foo
  ...

window.Foo = Foo

(其中 window.Foo = Foo 使 Foo 成为一个全局变量),并且 Bar 的文件应该以 Sprockets 指令开头

(where window.Foo = Foo makes Foo a global), and Bar's file should start with the Sprockets directive

#= require Foo

(假设您已将 Foo 的文件命名为 Foo.js.coffee).每个文件都是独立编译成JS的,但是Sprockets会保证Foo放在Bar之前.

(assuming that you've named Foo's file Foo.js.coffee). Each file is compiled into JS independently, but Sprockets will ensure that Foo is included before Bar.

请注意,作为一种快捷方式,您可以去掉 window.Foo = Foo 行,而改为编写

Note that, as a shortcut, you can get rid of the window.Foo = Foo line, and instead write

class window.Foo
  ...

或者干脆

class @Foo
  ...

定义一个名为 Foo 的类,该类附加到 window 对象.

to define a class named Foo that's attached to the window object.

这篇关于构建咖啡脚本代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆