/server/index.coffee
CoffeeScript | 76 lines | 56 code | 17 blank | 3 comment | 6 complexity | 823e4a27b5983a4f2ae1443eaeaf560f MD5 | raw file
- _ = require('underscore')._
- Backbone = require 'backbone'
- unicaster = require './unicaster'
- pubnub = require('pubnub').init
- publish_key: 'pub-c-6dd9f234-e11e-4345-92c4-f723de52df70'
- subscribe_key: 'sub-c-4c7f1748-ced1-11e2-a5be-02ee2ddab7fe'
- Todo = Backbone.Model.extend
- defaults: () ->
- {
- title: "empty todo..."
- order: Todos.nextOrder()
- done: false
- }
- toggle: () ->
- @save
- done: !@get 'done'
- TodoList = Backbone.Collection.extend
- model: Todo
- done: () ->
- @where { done: true }
- remaining: () ->
- @without.apply this, @done()
- remaining: () ->
- @without.apply this, @done()
- nextOrder: () ->
- if not @length then return 1
- @last().get('order') + 1
- comparator: 'order'
- Todos = new TodoList
- # Subscribe to the todo list updates
- pubnub.subscribe
- channel: 'backbone-collection-TodoList'
- callback: (data) ->
- console.log data
- if data.method is "create"
- Todos.add data.model
- else if data.method is "delete"
- Todos.remove data.model
- else if data.method is "update"
- unless not data.model.id
- record = _.find Todos.models, (record) ->
- record.id is data.model.id
- unless record?
- console.log "Could not find record: #{data.model.id}"
- return false
- diff = _.difference _.keys(record.attributes), _.keys(data.model)
- _.each diff, (key) ->
- record.unset key
- record.set data.model, data.options
- app = unicaster.listen pubnub
- # Return the list of todos
- app.on 'getTodos', (req, resp) ->
- resp.end Todos.toJSON()
- # For cloud deploying
- http = require 'http'
- app = http.createServer (req, res) ->
- res.writeHead 200, { 'Content-Type': 'text/html' }
- res.end 'Okay'
- app.listen process.env.PORT ? 5000