forked from mcbrumagin/meteor-events
-
Notifications
You must be signed in to change notification settings - Fork 0
/
events.coffee
58 lines (48 loc) · 1.79 KB
/
events.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
Events = new Meteor.Collection 'Events'
Events.handlers = {}
mergeNoConflict = (objTo, objFrom) ->
for k,v of objFrom
unless objTo[k]? then objTo[k] = v
else console.warn "Property '#{k}' already exists in object."
runHandler = (name, data...) ->
handlers = Events.handlers[name]
if handlers?.length > 0
(fn data...) for fn in handlers
upsert = (name, data...) ->
runHandler name, {server:!this.connection,client:this.userId}, data...
Events.upsert name:name,
$set: {data: data, date: new Date,server:!this.connection,client:this.userId},
(err, args...) ->
if err? then console.error 'update failed', err
#else console.log 'updated', (data.concat args)...
Meteor.methods event: upsert
updateEvent = (name, data...) ->
if Meteor.isClient
Meteor.call 'event', name, data..., (err, res) ->
if err? then console.error 'event call failed', err
#else console.log 'updated', (data.concat args)...
else upsert name, data...
bind = (name, fn) ->
handlers = Events.handlers[name]
if handlers? and fn?
handlers.push fn
Events.handlers[name] = handlers
else if fn? then Events.handlers[name] = [fn]
else console.error 'fn must be present', fn
if Meteor.isServer
mergeNoConflict Events,
on: (name, fn) -> bind name, fn
emit: (name, data...) ->
Meteor.publish "events-#{name}", (name) ->
Events.find name:name
updateEvent name, data...
else if Meteor.isClient
subscribeToEvent = (name, fn) ->
bind name, fn
Meteor.subscribe "events-#{name}", name
Events.find(name:name).observe
changed: (id, event) ->
if event? then fn {server:event.server,client:event.client}, event.data...
mergeNoConflict Events,
on: (name, fn) -> subscribeToEvent name, fn
emit: (name, args...) -> updateEvent name, args...