Skip to content

Commit

Permalink
client (browser) emitting events to server
Browse files Browse the repository at this point in the history
  • Loading branch information
zaitsev-oleksii committed Aug 17, 2022
1 parent be5faa0 commit cca92d7
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
16 changes: 15 additions & 1 deletion dist/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const warnAboutMemoryLeak = (eventName, count) =>
export default class EventEmitter {
constructor() {
this.events = new Map();
this.globalListeners = new Set();
this.maxListenersCount = 10;
}

Expand All @@ -33,6 +34,16 @@ export default class EventEmitter {
}
}

onAny(fn) {
const tooManyListeners = this.globalListeners.size > this.maxListenersCount;
if (tooManyListeners) warnAboutMemoryLeak('*', this.globalListeners.size);
this.globalListeners.add(fn);
}

clearGlobalListeners() {
this.globalListeners.clear();
}

once(name, fn) {
const dispose = (...args) => {
this.remove(name, dispose);
Expand All @@ -43,10 +54,13 @@ export default class EventEmitter {

emit(name, ...args) {
const event = this.events.get(name);
if (!event) return;
if (!event && !this.globalListeners.size) return;
for (const fn of event.values()) {
fn(...args);
}
for (const fn of this.globalListeners.values()) {
fn(name, ...args);
}
}

remove(name, fn) {
Expand Down
6 changes: 6 additions & 0 deletions dist/metacom.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export class Metacom extends EventEmitter {
this.calls = new Map();
this.streams = new Map();
this.streamId = 0;
this.eventId = 0;
this.active = false;
this.connected = false;
this.opening = null;
Expand Down Expand Up @@ -157,6 +158,11 @@ export class Metacom extends EventEmitter {
for (const methodName of methodNames) {
methods[methodName] = request(methodName);
}
methods.onAny((eventName, data) => {
const target = `${interfaceName}/${eventName}`;
const packet = { event: ++this.eventId, [target]: data };
this.send(JSON.stringify(packet));
});
this.api[interfaceName] = methods;
}
}
Expand Down

0 comments on commit cca92d7

Please sign in to comment.