-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessage-bus.js
43 lines (36 loc) · 1.14 KB
/
message-bus.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
(function(exports){
function MessageBus(target, options) {
if(!(this instanceof MessageBus)){
return new MessageBus(target, options);
}
target = target || window;
this.target = (window.parent === window ?
target.contentWindow :
target.parent) || target;
window.addEventListener('message', this.handle.bind(this));
return this;
};
MessageBus.prototype.send = function(message, to){
to = to || '*';
// console.debug('MessageBus#send', message);
this.target.postMessage(message, to);
return this;
};
MessageBus.prototype.on = function(type, fn){
this.handlers = this.handlers || {};
(this.handlers[type] = this.handlers[type] || []).push(fn);
return this;
};
MessageBus.prototype.fire = function(type, args){
args = [].slice.call(arguments, 1);
this.handlers = this.handlers || {};
(this.handlers[type] || []).forEach(fn => fn.apply(this, args));
return this;
};
MessageBus.prototype.handle = function(e){
this.fire('message', e.data, e);
// console.log('MessageBus#handle', e);
return this;
};
exports.MessageBus = MessageBus;
})(this);