Refactor messaging listerners.

This commit is contained in:
Richard Lewis 2017-11-30 10:20:29 +00:00
parent 4f5f44ff38
commit 2cfbbb000e
2 changed files with 36 additions and 34 deletions

View file

@ -1,5 +1,5 @@
/*
Copyright 2016 OpenMarket Ltd
Copyright 2017 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -14,38 +14,12 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
export default class WidgetMessaging {
constructor() {
this.listenerCount = 0;
}
/**
* Register widget message event listeners
* Handle widget postMessage events
* @param {Event} event Event to handle
* @return {undefined}
*/
registerListeners() {
if (this.listenerCount === 0) {
window.addEventListener("message", this.onMessage, false);
}
this.listenerCount += 1;
}
derigisterListeners() {
this.listenerCount -= 1;
if (this.listenerCount === 0) {
window.removeEventListener("message", this.onMessage);
}
if (this.listenerCount < 0) {
// Make an error so we get a stack trace
const e = new Error(
"WidgetMessaging: mismatched startListening / stopListening detected." +
" Negative count",
);
console.error(e);
}
}
onMessage(event) {
function onMessage(event) {
console.warn("Checking for widget event", event);
if (!event.origin) { // Handle chrome
event.origin = event.originalEvent.origin;
@ -60,4 +34,32 @@ export default class WidgetMessaging {
// TODO -- handle widget actions
alert(event.data.widgetData);
}
let listenerCount = 0;
module.exports = {
/**
* Register widget message event listeners
* @return {undefined}
*/
startListening() {
if (listenerCount === 0) {
window.addEventListener("message", onMessage, false);
}
listenerCount += 1;
},
stopListening() {
listenerCount -= 1;
if (listenerCount === 0) {
window.removeEventListener("message", onMessage);
}
if (listenerCount < 0) {
// Make an error so we get a stack trace
const e = new Error(
"WidgetMessaging: mismatched startListening / stopListening detected." +
" Negative count",
);
console.error(e);
}
},
};

View file

@ -153,8 +153,7 @@ export default React.createClass({
},
componentWillMount() {
this.widgetMessagingClient = new WidgetMessaging();
this.widgetMessagingClient.registerListeners();
WidgetMessaging.startListening();
window.addEventListener('message', this._onMessage, false);
this.setScalarToken();
},
@ -207,6 +206,7 @@ export default React.createClass({
},
componentWillUnmount() {
WidgetMessaging.stopListening();
window.removeEventListener('message', this._onMessage);
},