-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmediator.js
44 lines (35 loc) · 864 Bytes
/
mediator.js
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
'use strict'
/**
* Mediator
* - Controls communication between objects
* - One object manages all communication
* - Many to Many relationships
*/
let mediator = (function () {
let channels = {}
let subscribe = function (channel, context, func) {
if (!mediator.channels[channel]) {
mediator.channels[channel] = []
}
mediator.channels[channel].push({
context: context,
func: func
})
}
let publish = function (channel) {
if (!this.channels[channel]) {
return false
}
let args = Array.prototype.slice.call(arguments, 1)
for (let i = 0; i < mediator.channels[channel].length; i++) {
let sub = mediator.channels[channel][i]
sub.func.apply(sub.context, args)
}
}
return {
channels: channels,
subscribe: subscribe,
publish: publish
}
}())
module.exports = mediator