Structuring coffeescript code?

后端 未结 5 1023
花落未央
花落未央 2020-12-09 01:46

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

5条回答
  •  天命终不由人
    2020-12-09 02:41

    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.

提交回复
热议问题