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

/server/index.js

https://github.com/colincarr/pubnub-backbone
JavaScript | 101 lines | 85 code | 15 blank | 1 comment | 10 complexity | 7b3bcceb03c0d73aa206148f4d984ee0 MD5 | raw file
  1. // Generated by CoffeeScript 1.6.2
  2. (function() {
  3. var Backbone, Todo, TodoList, Todos, app, http, pubnub, unicaster, _, _ref;
  4. _ = require('underscore')._;
  5. Backbone = require('backbone');
  6. unicaster = require('./unicaster');
  7. pubnub = require('pubnub').init({
  8. publish_key: 'pub-c-6dd9f234-e11e-4345-92c4-f723de52df70',
  9. subscribe_key: 'sub-c-4c7f1748-ced1-11e2-a5be-02ee2ddab7fe'
  10. });
  11. Todo = Backbone.Model.extend({
  12. defaults: function() {
  13. return {
  14. title: "empty todo...",
  15. order: Todos.nextOrder(),
  16. done: false
  17. };
  18. },
  19. toggle: function() {
  20. return this.save({
  21. done: !this.get('done')
  22. });
  23. }
  24. });
  25. TodoList = Backbone.Collection.extend({
  26. model: Todo,
  27. done: function() {
  28. return this.where({
  29. done: true
  30. });
  31. },
  32. remaining: function() {
  33. return this.without.apply(this, this.done());
  34. },
  35. remaining: function() {
  36. return this.without.apply(this, this.done());
  37. },
  38. nextOrder: function() {
  39. if (!this.length) {
  40. return 1;
  41. }
  42. return this.last().get('order') + 1;
  43. },
  44. comparator: 'order'
  45. });
  46. Todos = new TodoList;
  47. pubnub.subscribe({
  48. channel: 'backbone-collection-TodoList',
  49. callback: function(data) {
  50. var diff, record;
  51. console.log(data);
  52. if (data.method === "create") {
  53. return Todos.add(data.model);
  54. } else if (data.method === "delete") {
  55. return Todos.remove(data.model);
  56. } else if (data.method === "update") {
  57. if (!!data.model.id) {
  58. record = _.find(Todos.models, function(record) {
  59. return record.id === data.model.id;
  60. });
  61. if (record == null) {
  62. console.log("Could not find record: " + data.model.id);
  63. return false;
  64. }
  65. diff = _.difference(_.keys(record.attributes), _.keys(data.model));
  66. _.each(diff, function(key) {
  67. return record.unset(key);
  68. });
  69. return record.set(data.model, data.options);
  70. }
  71. }
  72. }
  73. });
  74. app = unicaster.listen(pubnub);
  75. app.on('getTodos', function(req, resp) {
  76. return resp.end(Todos.toJSON());
  77. });
  78. http = require('http');
  79. app = http.createServer(function(req, res) {
  80. res.writeHead(200, {
  81. 'Content-Type': 'text/html'
  82. });
  83. return res.end('Okay');
  84. });
  85. app.listen((_ref = process.env.PORT) != null ? _ref : 5000);
  86. }).call(this);