forked from aranm/scalable-javascript-architecture
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Core.Communication.js
93 lines (79 loc) · 2.74 KB
/
Core.Communication.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*globals Core, require*/
//inter-module communication methods
(function () {
var coreCommunication = function () {
//object containing all the handler functions
var slice = [].slice, handlers = {};
return {
addListener: function (topic, callback, context) {
var type = topic;
if (!handlers[type]) {
handlers[type] = [];
}
handlers[type].push({ context: context, callback: callback });
},
notify: function (topic) {
if (!handlers[topic]) {
return true;
}
var args = slice.call(arguments, 1),
type = topic,
ret = true,
i,
len,
msgList;
if (handlers[type] instanceof Array) {
msgList = handlers[type];
for (i = 0, len = msgList.length; i < len && ret === true; i++) {
ret = msgList[i].callback.apply(msgList[i].context, args);
if (ret === undefined) {
ret = true;
}
}
}
return ret;
},
removeListener: function (topic, callbackFunction) {
var type = topic, callback = callbackFunction, handlersArray = handlers[type], i, len;
if (handlersArray instanceof Array) {
for (i = 0, len = handlersArray.length; i < len; i++) {
if (handlersArray[i].callback === callback) {
break;
}
}
handlers[type].splice(i, 1);
}
},
removeAllListeners: function () {
handlers = {};
},
removeAllListenersForContext: function (messageContext) {
//TODO: this method is unfinished
var context = messageContext, handlersArray, i, j;
for (j = handlers.length; j >= 0; j++) {
handlersArray = handlers[j];
if (handlersArray instanceof Array) {
for (i = handlersArray.length; i >= 0; i--) {
if (handlersArray[i].context === messageContext) {
handlersArray.splice(i, 1);
}
}
if (handlers[j].length === 0) {
handlers.splice(j, 1);
}
}
}
}
};
};
// Expose Core as an AMD module
if (typeof define === "function" && define.amd) {
define("Core.Communication", ["Core"], function (core) {
core.Communication = coreCommunication();
return core.Communication;
});
}
else {
Core.Communication = coreCommunication();
}
})();