/
nodes.js
89 lines (74 loc) · 2.33 KB
/
nodes.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
(function($) {
$inplace.MessageTrapException = { type: 'message-trap' };
$inplace.Message = function(topic, sender, data) {
this.topic = topic;
this.sender = sender;
this.data = data;
};
$inplace.Node = $inplace.Meta.clone()
.extend({
hasConstructor: function(options) {
this.__childs = [];
this.__downstreamHandlers = {};
this.__upstreamHandlers = {};
},
appendChild: function(child) {
this.__childs.push(child);
child.parentNode = this;
return this;
},
messageHandler: function(msg){
var handlers = this.__downstreamHandlers[msg.topic];
if(handlers) {
$.each(handlers, function(handler) {
handler(msg);
});
}
},
childMessageHandler: function(msg){
var handlers = this.__upstreamHandlers[msg.topic];
if(handlers) {
$.each(handlers, function(handler) {
handler(msg);
});
}
},
sendMessage: function(msg) {
this._processMessage(msg);
},
sendParentMessage: function(msg){
if(!this.parentNode) return this;
this.parentNode._processChildMessage(msg);
return this;
},
_processChildMessage: function(msg) {
try {
this.childMessageHandler(msg);
if(!this.parentNode) return;
this.parentNode._processChildMessage(msg);
} catch (exc) {
console.log('Exception while sending message to parent: '+exc.type);
}
},
_processMessage: function(msg) {
try {
this.messageHandler(msg);
if(this.__childs) {
$.each(this.__childs, function(child) {
child._processMessage(msg);
});
}
} catch (exc) {
console.log("Exception while processing broadcast message: "+exc.type);
}
},
subscribe: function(topic, handler) {
this.__downstreamHandlers[topic] = this.__downstreamHandlers[topic] || [];
this.__downstreamHandlers[topic].push(handler);
},
subscribeUpstream: function(topic, handler) {
this.__upstreamHandlers[topic] = this.__upstreamHandlers[topic] || [];
this.__upstreamHandlers[topic].push(handler);
}
});
})(jQuery);