Skip to content

Commit c0f00d6

Browse files
committed
Refactor disconnecting
1 parent 0397dfe commit c0f00d6

File tree

1 file changed

+19
-26
lines changed

1 file changed

+19
-26
lines changed

src/app/middlewares/api.js

Lines changed: 19 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -112,10 +112,25 @@ function messaging(request, sender, sendResponse) {
112112
toMonitors(action, tabId);
113113
}
114114

115+
function disconnect(type, id, listener) {
116+
return function disconnectListener() {
117+
if (type === 'tab') {
118+
window.store.dispatch({ type: REMOVE_INSTANCE, id });
119+
toMonitors(naMessage);
120+
} else {
121+
monitors--;
122+
if (!monitors) monitorInstances(false);
123+
}
124+
const p = connections[type][id];
125+
if (listener) p.onMessage.removeListener(listener);
126+
p.onDisconnect.removeListener(disconnectListener);
127+
delete connections[type][id];
128+
};
129+
}
130+
115131
function onConnect(port) {
116132
let id;
117133
let listener;
118-
let disconnect;
119134

120135
window.store.dispatch({ type: CONNECTED, port });
121136

@@ -132,28 +147,14 @@ function onConnect(port) {
132147
messaging(msg.message, port.sender, id);
133148
}
134149
};
135-
disconnect = () => {
136-
const p = connections.tab[id];
137-
p.onMessage.removeListener(listener);
138-
p.onDisconnect.removeListener(disconnect);
139-
delete connections.tab[id];
140-
window.store.dispatch({ type: REMOVE_INSTANCE, id });
141-
toMonitors(naMessage);
142-
};
143150
port.onMessage.addListener(listener);
144-
port.onDisconnect.addListener(disconnect);
151+
port.onDisconnect.addListener(disconnect('tab', id, listener));
145152
} else if (port.name === 'monitor') {
146153
id = getId(port.sender);
147154
connections.monitor[id] = port;
148155
monitorInstances(true);
149156
monitors++;
150-
disconnect = () => {
151-
monitors--;
152-
connections.monitor[id].onDisconnect.removeListener(disconnect);
153-
delete connections.monitor[id];
154-
if (!monitors) monitorInstances(false);
155-
};
156-
port.onDisconnect.addListener(disconnect);
157+
port.onDisconnect.addListener(disconnect('monitor', id));
157158
} else {
158159
id = port.name;
159160
connections.panel[id] = port;
@@ -162,16 +163,8 @@ function onConnect(port) {
162163
listener = msg => {
163164
window.store.dispatch(msg);
164165
};
165-
disconnect = () => {
166-
monitors--;
167-
const p = connections.panel[id];
168-
p.onMessage.removeListener(listener);
169-
p.onDisconnect.removeListener(disconnect);
170-
delete connections.panel[id];
171-
if (!monitors) monitorInstances(false);
172-
};
173166
port.onMessage.addListener(listener);
174-
port.onDisconnect.addListener(disconnect);
167+
port.onDisconnect.addListener(disconnect('panel', id, listener));
175168
}
176169
}
177170

0 commit comments

Comments
 (0)