Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

ruby on rails 3 - Structuring coffeescript code?

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

class Foo
  ...

class Bar extends Foo
  ...

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

class Foo
  ...

window.Foo = Foo

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

#= require Foo

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

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

class window.Foo
  ...

or simply

class @Foo
  ...

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...