PageRenderTime 43ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/server/index.coffee

https://github.com/colincarr/pubnub-backbone
CoffeeScript | 76 lines | 56 code | 17 blank | 3 comment | 6 complexity | 823e4a27b5983a4f2ae1443eaeaf560f MD5 | raw file
  1. _ = require('underscore')._
  2. Backbone = require 'backbone'
  3. unicaster = require './unicaster'
  4. pubnub = require('pubnub').init
  5. publish_key: 'pub-c-6dd9f234-e11e-4345-92c4-f723de52df70'
  6. subscribe_key: 'sub-c-4c7f1748-ced1-11e2-a5be-02ee2ddab7fe'
  7. Todo = Backbone.Model.extend
  8. defaults: () ->
  9. {
  10. title: "empty todo..."
  11. order: Todos.nextOrder()
  12. done: false
  13. }
  14. toggle: () ->
  15. @save
  16. done: !@get 'done'
  17. TodoList = Backbone.Collection.extend
  18. model: Todo
  19. done: () ->
  20. @where { done: true }
  21. remaining: () ->
  22. @without.apply this, @done()
  23. remaining: () ->
  24. @without.apply this, @done()
  25. nextOrder: () ->
  26. if not @length then return 1
  27. @last().get('order') + 1
  28. comparator: 'order'
  29. Todos = new TodoList
  30. # Subscribe to the todo list updates
  31. pubnub.subscribe
  32. channel: 'backbone-collection-TodoList'
  33. callback: (data) ->
  34. console.log data
  35. if data.method is "create"
  36. Todos.add data.model
  37. else if data.method is "delete"
  38. Todos.remove data.model
  39. else if data.method is "update"
  40. unless not data.model.id
  41. record = _.find Todos.models, (record) ->
  42. record.id is data.model.id
  43. unless record?
  44. console.log "Could not find record: #{data.model.id}"
  45. return false
  46. diff = _.difference _.keys(record.attributes), _.keys(data.model)
  47. _.each diff, (key) ->
  48. record.unset key
  49. record.set data.model, data.options
  50. app = unicaster.listen pubnub
  51. # Return the list of todos
  52. app.on 'getTodos', (req, resp) ->
  53. resp.end Todos.toJSON()
  54. # For cloud deploying
  55. http = require 'http'
  56. app = http.createServer (req, res) ->
  57. res.writeHead 200, { 'Content-Type': 'text/html' }
  58. res.end 'Okay'
  59. app.listen process.env.PORT ? 5000