Skip to content

Instantly share code, notes, and snippets.

@ryanjones
Last active December 15, 2015 10:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanjones/5246118 to your computer and use it in GitHub Desktop.
Save ryanjones/5246118 to your computer and use it in GitHub Desktop.
CoffeeScript Cheat Sheet (CS 1.6)

Best Practices (no framework)

  • Method instantiation and method calls need parans () (ie. bus.drive(), new Bus())
  • Minimize dom selectors in classes (pass in dom elements into class constructor)

Class

class Bus
  constructor: ->

class Bus
  constructor: (@var1, @var2) ->

Instance methods (public function/properties)

class Bus
  constructor: ->

  drive: ->
    console.log "driving!!"

b = new Bus()
b.drive()

Instance methods (private function/properties)

class Bus
  constructor: ->
  
  _checkGas = ->
    console.log "checking each bus's gas level"
    
  echoGas: ->
    _checkGas()
    
b = new Bus()
b.echoGas()
b._checkGas() # error no method _checkGas

Calling instance method (from within instance)

class Bus
  constructor: ->
    @drive()

  drive: ->
    console.log "driving!!"

new Bus()

Class Methods

class Bus
  constructor: ->

  # preferred (personally)
  @honkHorn: ->
    console.log "Beep beep!!"

  # same as above
  @shootLaser= ->
    console.log "Pew pew!!"

Bus.honkHorn()
Bus.shootLaser()

Pass in dom element:

class Bus
  constructor: (@domElement) ->
    @drive()

  drive: ->
    console.log "driving!!"
    @domElement.hide()

new Bus($('ninjaDomElement'))

Namespaces

@ABC = window.ABC ? {}

# The above will allow you to do this:
class ABC.Bus
  constructor: ->
  

Turbolinks

Good

$(document).on "page:load", ->
  new RandomObject()

!!!!Bad!! (when binding you need a function as turbolinks will call .apply later on and explode)

# BAD
$(document).on "page:load", new RandomObject()
# BAD

Common Errors

Make sure you're setting the context of "this" properly

# BAD
  setupClickEvent: ->
    $('test').click ->
      @randomMethod()
# BAD
  
# Upon click: Uncaught TypeError: Object [object HTMLAnchorElement] has no method 'randomMethod' 

# if you want to call a method on the actual instance of the class
  setupClickEvent: ->
    $('test').click =>
      @randomMethod()      
      
# if you want to reference the current item the click event is on:
  setupClickEvent: ->
    $('test').click ->
      @.html()
      
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment