You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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()