Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 957
plang Avatar asked May 27 '11 09:05

plang


People also ask

How do you write a CoffeeScript?

In general, we use parenthesis while declaring the function, calling it, and also to separate the code blocks to avoid ambiguity. In CoffeeScript, there is no need to use parentheses, and while creating functions, we use an arrow mark (->) instead of parentheses as shown below.

Is CoffeeScript obsolete?

As of today, January 2020, CoffeeScript is completely dead on the market (though the GitHub repository is still kind of alive).

Is CoffeeScript easy?

CoffeeScript is a lightweight language that compiles into JavaScript. It provides simple and easy to learn syntax avoiding the complex syntax of JavaScript.

What is CoffeeScript written in?

CoffeeScript is a little language that compiles into JavaScript. Underneath that awkward Java-esque patina, JavaScript has always had a gorgeous heart.


1 Answers

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.

like image 128
Trevor Burnham Avatar answered Oct 03 '22 00:10

Trevor Burnham