summaryrefslogtreecommitdiffstats
path: root/coffee/lib/services/publisher.coffee
blob: 4d8788726d2b029bce0e5be00f29444fa63af3f0 (plain)
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
###
# ownCloud
#
# @author Bernhard Posselt
# Copyright (c) 2012 - Bernhard Posselt <nukeawhale@gmail.com>
#
# This file is licensed under the Affero General Public License version 3 or later.
# See the COPYING-README file
#
###

###
# Used for properly distributing received model data from the server
###
angular.module('OC').factory '_Publisher', ->


	class Publisher

		constructor: ->
			@subscriptions = {}


		# Use this to subscribe to a certain hashkey in the returned json data
		# dictionary.
		# If you send JSON from the server, you'll receive something like this
		#
		# 	{
		#		data: {
		#			modelName: {
		#				create: [{id: 1, name: 'john'}, {id: 2, name: 'ron'}],
		#               update: [],
		#               delete: []
		#           }
		#		}
		# 	}
		#
		# To get the array ['one', 'two'] passed to your model, just subscribe
		# to the key:
		#	Publisher.subscribeModelTo('modelName', myModelInstance)
		#
		subscribeModelTo: (model, name) ->
			@subscriptions[name] or= []
			@subscriptions[name].push(model)


		# This will publish data from the server to all registered subscribers
		# The parameter 'name' is the name under which subscribers have registered
		publishDataTo: (data, name) ->
			for subscriber in @subscriptions[name] || []
				subscriber.handle(data)


	return Publisher