isea isea - 3 months ago 15
CoffeeScript Question

Keep common js functions in a file to be used throughout application

I have Rails app using Asset Pipeline. There are many js files associated with different parts of the app. To keep it DRY I want to start pulling some of the repetitive code into a file and use those methods throughout the app. What I am attempting right now isn't working.

common.js.coffee

common =
some_commonly_used_method: ->
// code


Some_other_page_speciific_file.js.coffee

common.some_commonly_used_method()


browser console when I load the page


Uncaught ReferenceError: common is not defined


What do I need to do to have common.whatever available throughout the app?

Answer

Putting it in the window object ended up being my solution. I'm not sure it's ideal, but it works.

common.js.coffee

window.common =
  some_commonly_used_method: ->
    // code

Some_other_page_speciific_file.js.coffee

window.common.some_commonly_used_method()