/app/templates/client/components/socket(socketio)/socket.service(coffee).coffee

https://gitlab.com/javajamesb08/generator-angular-fullstack · CoffeeScript · 67 lines · 27 code · 13 blank · 27 comment · 1 complexity · 20b76cbcce2f735f52ac90bde0956afa MD5 · raw file

  1. # global io
  2. 'use strict'
  3. angular.module '<%= scriptAppName %>'
  4. .factory 'socket', (socketFactory) ->
  5. # socket.io now auto-configures its connection when we omit a connection url
  6. ioSocket = io '',
  7. # Send auth token on connection, you will need to DI the Auth service above
  8. # 'query': 'token=' + Auth.getToken()
  9. path: '/socket.io-client'
  10. socket = socketFactory ioSocket: ioSocket
  11. socket: socket
  12. ###
  13. Register listeners to sync an array with updates on a model
  14. Takes the array we want to sync, the model name that socket updates are sent from,
  15. and an optional callback function after new items are updated.
  16. @param {String} modelName
  17. @param {Array} array
  18. @param {Function} callback
  19. ###
  20. syncUpdates: (modelName, array, callback) ->
  21. ###
  22. Syncs item creation/updates on 'model:save'
  23. ###
  24. socket.on modelName + ':save', (item) ->
  25. oldItem = _.find array,
  26. _id: item._id
  27. index = array.indexOf oldItem
  28. event = 'created'
  29. # replace oldItem if it exists
  30. # otherwise just add item to the collection
  31. if oldItem
  32. array.splice index, 1, item
  33. event = 'updated'
  34. else
  35. array.push item
  36. callback? event, item, array
  37. ###
  38. Syncs removed items on 'model:remove'
  39. ###
  40. socket.on modelName + ':remove', (item) ->
  41. event = 'deleted'
  42. _.remove array,
  43. _id: item._id
  44. callback? event, item, array
  45. ###
  46. Removes listeners for a models updates on the socket
  47. @param modelName
  48. ###
  49. unsyncUpdates: (modelName) ->
  50. socket.removeAllListeners modelName + ':save'
  51. socket.removeAllListeners modelName + ':remove'