PageRenderTime 39ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://gitlab.com/javajamesb08/generator-angular-fullstack
JavaScript | 74 lines | 37 code | 10 blank | 27 comment | 3 complexity | 66bc7ea2524a7cfab97728b5bd05e601 MD5 | raw file
  1. /* global io */
  2. 'use strict';
  3. angular.module('<%= scriptAppName %>')
  4. .factory('socket', function(socketFactory) {
  5. // socket.io now auto-configures its connection when we ommit a connection url
  6. var 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. });
  11. var socket = socketFactory({
  12. ioSocket: ioSocket
  13. });
  14. return {
  15. socket: socket,
  16. /**
  17. * Register listeners to sync an array with updates on a model
  18. *
  19. * Takes the array we want to sync, the model name that socket updates are sent from,
  20. * and an optional callback function after new items are updated.
  21. *
  22. * @param {String} modelName
  23. * @param {Array} array
  24. * @param {Function} cb
  25. */
  26. syncUpdates: function (modelName, array, cb) {
  27. cb = cb || angular.noop;
  28. /**
  29. * Syncs item creation/updates on 'model:save'
  30. */
  31. socket.on(modelName + ':save', function (item) {
  32. var oldItem = _.find(array, {_id: item._id});
  33. var index = array.indexOf(oldItem);
  34. var event = 'created';
  35. // replace oldItem if it exists
  36. // otherwise just add item to the collection
  37. if (oldItem) {
  38. array.splice(index, 1, item);
  39. event = 'updated';
  40. } else {
  41. array.push(item);
  42. }
  43. cb(event, item, array);
  44. });
  45. /**
  46. * Syncs removed items on 'model:remove'
  47. */
  48. socket.on(modelName + ':remove', function (item) {
  49. var event = 'deleted';
  50. _.remove(array, {_id: item._id});
  51. cb(event, item, array);
  52. });
  53. },
  54. /**
  55. * Removes listeners for a models updates on the socket
  56. *
  57. * @param modelName
  58. */
  59. unsyncUpdates: function (modelName) {
  60. socket.removeAllListeners(modelName + ':save');
  61. socket.removeAllListeners(modelName + ':remove');
  62. }
  63. };
  64. });