Coffee Script Memo

From last week i tried the Ember-Rails and studied the coffee script btw. Because more and more people use coffee script and i want to understand their codes! In the beginning the coffee script syntax confuses me a lot and cost a lot of time to google it. I decide to keep it on post for reference in the future.

The indent is the most important to coffeescript. Wrong indent cause compile fail. For example: define a method to call ajax. You can insert variable into string using "#{}". @successHandle is the same as this.successHandle.

1
2
3
4
5
6
7
8
9
getData: ->
  $.ajax '/api/post/',
    type: 'GET'
    dataType: 'json'
    success: (data, textStatus, jqXHR) ->
      @successHandle data

    successHandle: (data) ->
      console.log "success #{data}"

Pass a string and function. For example: listen a click event

1
2
button.addListener 'click',() ->
  console.log 'btn click'

All variable definition will be scoped in function. If you want to def a variable in each loop, you should use do () ->

1
2
3
4
5
6
7
8
9
10
11
12
check = () ->
  for person in people
    post = new Post()
    person.setPost post
#every person has the same post reference

check = () ->
  for person in people
    do (person) ->
      post = new Post()
      person.setPost post
#every person has his post

iterate a hash object

1
2
3
4
5
6
7
hashobject =
  name: 'ben'
  address: 'xxxxx'

for key, value of hashobject
  console.log key
  console.log value

timeout syntax

1
2
3
setTimeout (->
  console.log "hello world"
), 100

loop a array from middle

Usually we use below to iter a array

1
2
3
myarray = [1..5]
for element in myarray
  console.log element # output 1~5

Can strat from index 2, index is from 0. Means from third element

1
2
for index in [2...myarray.length]
  console.log myarray[index] # output 3~5

ternary opeartor

1
2
3
console.log if 10>5 ? "hi" : "bye" # Compile ERROR

console.log if 10>5 then "hi" else "bye" # output hi

set value using ?=

If you use ?= you have to declare ‘instance = null’ first.

1
2
3
4
5
6
7
instance = null # without this, Compile ERROR
instance ?= "abc"
console.log instance # output abc

# the old way.
instance2 = instance2 || "abc"
console.log instance2 # output abc

regular expression

Put regular exprssion in /// /// block

1
2
3
4
5
6
7
summaries_pattern = ///
  summaries.*
///

msg = "the final summaries is good"
if msg.match summaries_pattern
  console.log 'good job'

Comments