Last active
October 13, 2018 18:27
-
-
Save marihachi/457d13625b7e8b53f7331547434443a3 to your computer and use it in GitHub Desktop.
xevを使ったpubsub(observerパターン?)実装 [MIT License: (c) 2018 Marihachi]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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