Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared JS (Coffee) in Rails

If I want to share some JavaScript function between different files under app/assets/javascript what would be the best way to I organise the directory structure?

Let's say I have shared.js.coffee

sharedFunction = ->
  'Hello '

Now, how can I use it in some other place? Like here, in welcome.js.coffee

welcome = (name) ->
  sharedFunction() + name

How can I make shared.js.cofee always be loaded first?

I tried to put it in the very beginning of application.js, but it doesn't change anything. Seems shared file loading too long, and welcome manages to start executing and notice that sharedFunction is not defined.

like image 548
Misha Slyusarev Avatar asked Dec 16 '22 03:12

Misha Slyusarev


1 Answers

I do it in this way:

  • Ensure you require the file in application.js before anything else, expecially before require_tree
  • Export the functions (in my case a class, so it's namespaced)

Example: (Suppose we have application.js and shared.js.coffee at same level)

application.js

//= require ./shared
//= require_tree .

shared.js.coffee

class MyNamespace
  @mySharedFunc: () ->
    doSomething()

root             = exports ? this
root.MyNamespace = MyNamespace

You can now easily access in your other coffeescript files the function by referencing it in this way MyNamespace.mySharedFunc()

P.S.

The misterious thing about exports is explained very well in this stackoverflow question: How do I define global variables in CoffeeScript?

like image 135
Francesco Belladonna Avatar answered Dec 17 '22 16:12

Francesco Belladonna