-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
68 lines (54 loc) · 1.4 KB
/
index.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
var Emitter = require('emitter'),
attach = window.addEventListener ? 'addEventListener' : 'attachEvent',
detach = window.removeEventListener ? 'removeEventListener' : 'detachEvent',
prefix = attach !== 'addEventListener' ? 'on' : '';
//TODO: we could encapsulte an id into the postMessage message
//Example
// message = [...];
// message._id = "...";
//
// but it'd mean that it could only receive messages from an other post component.
/**
* Expose 'PostEmitter'
*/
module.exports = PostEmitter;
/**
* PostEmitter constructor.
* Listen local and remote messages.
*
* @api public
*/
function PostEmitter(obj) {
var _this = this;
//might be global
this._listener = function(ev) {
//check origin
//then
var data = ev.data;
_this.emit.apply(_this, data instanceof Array ? data : [data]);
};
window[attach](prefix + 'message', this._listener);
}
Emitter(PostEmitter.prototype);
/**
* Emit local or cross-origin messages.
* @param {String} topic
* @param {Amy}
* @return {Function}
* @api public
*/
PostEmitter.prototype.emit = function() {
var args = arguments;
Emitter.prototype.emit.apply(this, args);
return function(domain) {
window.postMessage([].slice.call(args), domain || window.location.href);
};
};
/**
* Remove post message listener.
* @api public
*/
PostEmitter.prototype.dispose = function() {
window[detach](prefix + 'message', this._listener);
this.off();
};