Skip to content

Instantly share code, notes, and snippets.

@philmill
Last active August 29, 2015 14:14
Show Gist options
  • Save philmill/651b4c36d445e9158f02 to your computer and use it in GitHub Desktop.
Save philmill/651b4c36d445e9158f02 to your computer and use it in GitHub Desktop.
CoffeeScript Niceties
# jQuery(function($){
# });
# can be re-written as
jQuery ($) ->
console.log 'stuff'
# or if jQuery is only one useing $
$ ->
console.log 'stuff'
$(this) is $(@) # true
# why not use interpolation in a selector
$("<li>#{name}</li>")
# chained comparisons
if 2 > x < 5 then console.log 'range!'
# switch case
message = switch numOfThing
when 0 then 'hi'
when 1 then 'bye'
else 'world'
# ruby like #try(:my_method) using existential
obj?.myMethod() # if we don't know the state of obj
obj.myMethod?() # if we don't know myMethod is defined on obj
# setting default with existential
obj ?= 0
# array without commas
values = [
'stuff'
'fun'
'other'
]
# lets loop them
for value in values
alert "My Value is #{value}"
# or, where our return value preceeds the interation (this is a comprehension!)
alert "My Value is #{value}" for value in values
# lets mutate our values array
values = ("Mutated #{value}" for value in values)
# lets call a method with our values except when its 'other' using a filter
myMethod(value) for value in values when value isnt 'other'
# and build a new array with our values except for 'other'
newValues = (value for value in values when value isnt 'other')
# variable number or function args
myMethod = (requiredArg, varArg...) ->
"this is required #{requiredArg} and this is an array #{varArg.join(',')}"
# passing args in
myMethod 'required', 'arg1', 'arg2'
# or
params = [
'required'
'arg1'
'arg2'
]
myMethod(params...)
# Hashes
myHash = key: 'value', key2: 'value2'
# or
myHash =
key: 'value'
key2: 'value2'
fun: -> alert("reference key2 like #{@key2}")
myHash.fun() # alert with 'reference key2 like value2'
# deeper
myHash =
level0:
level1: 1
myHash.level0.level1 is 1 # true
# iterate that Hash!
for key, value of myHash
"#{key} with #{value.level1}"
# or
"#{key} with #{value.level1}" for key, value of myHash
# both return ["level0 with 1"]
# binding the current value of this using a class example
class NotjQuery
constructor: (@name, @value=1) ->
ourMethod: ->
$('#someId').click (event) =>
if @name isnt 'jQuery'
@value += 1
alert "This is #{@name}"
# without the fat arrow,
# @name would be in the context of $('#someId') not our class
# create an instance
nj = new NotjQuery('hi', 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment