Last Updated: February 25, 2016
·
873
· ttoni

Global variables/classes in Coffeescript

Many times there is a point where an app underwent several small frontend changes and calls for refactoring. Thi usually leads to a more OO and modular approach on the frontend.

One of the obstacles I encountered at the beginning is separating my Classes and its instances on different .coffee files and at the same time being able to access them from any other file.

This is the approach that worked best for me.

First, we declare an empty context where all our frontend logic will reside in:

$ ->
  this.superapp ={}
  #Other interesting initializations for your app such as defaults etc

And here one example of a class using the lovely x-editable library:

$ ->
  class Editable
    constructor: ()->
      this.make_editable()
    make_editable: ()->
      $('a.editable').editable()

  this.superapp.xeditable = new Editable()

Now at any other file in my project I can access the x-editable instance of my frontend. For example, I like to fill the contents of my modals via ajax, that's why I need to make some of the fields that the ajax responds editable:

$ ->
  $('a#trigger-modal').on 'click', ->
    #append responde of /get_content to the modal container
    $('div.modal-content').load '/get_content', ->
      #make new appended fields x-editable
      superapp.xeditable.make_editable()

Simple!