-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathsocket.service(coffee).coffee
67 lines (51 loc) · 1.63 KB
/
socket.service(coffee).coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# global io
'use strict'
angular.module '<%= scriptAppName %>'
.factory 'socket', (socketFactory) ->
# socket.io now auto-configures its connection when we omit a connection url
ioSocket = io '',
'reconnection limit': 10 * 1000
# Send auth token on connection, you will need to DI the Auth service above
# 'query': 'token=' + Auth.getToken()
socket = socketFactory ioSocket: ioSocket
socket: socket
###
Register listeners to sync an array with updates on a model
Takes the array we want to sync, the model name that socket updates are sent from,
and an optional callback function after new items are updated.
@param {String} modelName
@param {Array} array
@param {Function} callback
###
syncUpdates: (modelName, array, callback) ->
###
Syncs item creation/updates on 'model:save'
###
socket.on modelName + ':save', (item) ->
oldItem = _.find array,
_id: item._id
index = array.indexOf oldItem
event = 'created'
# replace oldItem if it exists
# otherwise just add item to the collection
if oldItem
array.splice index, 1, item
event = 'updated'
else
array.push item
callback? event, item, array
###
Syncs removed items on 'model:remove'
###
socket.on modelName + ':remove', (item) ->
event = 'deleted'
_.remove array,
_id: item._id
callback? event, item, array
###
Removes listeners for a models updates on the socket
@param modelName
###
unsyncUpdates: (modelName) ->
socket.removeAllListeners modelName + ':save'
socket.removeAllListeners modelName + ':remove'