Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Client (browser) emitting events to server #346

Merged
merged 6 commits into from
Aug 24, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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