-
Notifications
You must be signed in to change notification settings - Fork 286
/
Copy pathport-mixin.js
47 lines (38 loc) · 1.08 KB
/
port-mixin.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
const Ember = window.Ember;
const { Mixin } = Ember;
export default Mixin.create({
port: null,
messages: {},
portNamespace: null,
init() {
this._super(...arguments);
this.setupOrRemovePortListeners('on');
},
willDestroy() {
this._super(...arguments);
this.setupOrRemovePortListeners('off');
},
sendMessage(name, message) {
this.get('port').send(this.messageName(name), message);
},
messageName(name) {
let messageName = name;
if (this.get('portNamespace')) {
messageName = `${this.get('portNamespace')}:${messageName}`;
}
return messageName;
},
/**
* Setup or tear down port listeners. Call on `init` and `willDestroy`
* @param {String} onOrOff 'on' or 'off' the functions to call i.e. port.on or port.off for adding or removing listeners
*/
setupOrRemovePortListeners(onOrOff) {
let port = this.get('port');
let messages = this.get('messages');
for (let name in messages) {
if (messages.hasOwnProperty(name)) {
port[onOrOff](this.messageName(name), this, messages[name]);
}
}
}
});