Skip to content

Instantly share code, notes, and snippets.

@marihachi
Last active October 13, 2018 18:27
Show Gist options
  • Select an option

  • Save marihachi/457d13625b7e8b53f7331547434443a3 to your computer and use it in GitHub Desktop.

Select an option

Save marihachi/457d13625b7e8b53f7331547434443a3 to your computer and use it in GitHub Desktop.
xevを使ったpubsub(observerパターン?)実装 [MIT License: (c) 2018 Marihachi]
const Xev = require('xev').default;
const { EventEmitter } = require('events');
class XevPubSub extends EventEmitter {
constructor(namespace) {
super();
this.parentEmitter = new Xev(namespace);
this.list = {};
this.handler = (channel) => (message) => this.emit('message', channel, message);
}
subscribe(channelName) {
if (this.list[channelName] == null) {
const handler = this.handler(channelName);
this.parentEmitter.on(channelName, handler);
this.list[channelName] = handler;
}
}
unsubscribe(channelName) {
if (this.list[channelName] != null) {
this.parentEmitter.removeListener(channelName, this.list[channelName]);
this.list[channelName] = null;
}
}
publish(channelName, message) {
this.parentEmitter.emit(channelName, message);
}
dispose() {
for (const channel of Object.keys(this.list)) {
this.unsubscribe(channel);
}
this.parentEmitter.dispose();
}
}
module.exports = XevPubSub;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment