Sample CoffeeScript# Assignment: # Splats:number = 42 race = (winner, runners...) ->opposite = true print winner, runners# Conditions: # Existence:number = -42 if opposite alert "I knew it!" if elvis?# Functions: # Array comprehensions:square = (x) -> x * x cubes = (math.cube num for num in list)# Arrays:list = [1, 2, 3, 4, 5]# Objects:math = root: Math.sqrt square: square cube: (x) -> x * square x
Backbone.js model in CoffeeScriptclass window.Todo extends Backbone.Model # If you dont provide a todo, one will be provided for you. EMPTY: "empty todo..." # Ensure that each todo created has `content`. initialize: -> unless this.get "content" this.set content: this.EMPTY # Toggle the `done` state of this todo item. toggle: -> this.save done: !this.get "done"
Collection of modelsclass window.TodoList extends Backbone.Collection # Reference to this collections model. model: Todo url: /todos # Filter down the list of all todo items that are finished. done: -> this.filter (todo) -> todo.get done # Filter down the list to only todo items that are still not finished. remaining: -> this.without this.done()... nextOrder: -> return 1 unless @length this.last().get(order) + 1 # Todos are sorted by their original insertion order. comparator: (todo) -> todo.get order
Sample Jasmine testsdescribe "Todo", -> todo = null ajaxCall = (param) -> jQuery.ajax.mostRecentCall.args[param] beforeEach -> todo = new Todo todos = new TodoList [todo] it "should initialize with empty content", -> expect(todo.get "content").toEqual "empty todo..." it "should initialize as not done", -> expect(todo.get "done").toBeFalsy() it "should save after toggle", -> spyOn jQuery, "ajax" todo.toggle() expect(ajaxCall "url").toEqual "/todos" expect(todo.get "done").toBeTruthy()