* Generic port message handler that can be attached via port.onMessage.addListener(). * Once set up, events can be handled with on('event', function(options) {}) * @param {String} options.event The event descriptor * @param {Object} options Contains message attributes and data
(options = {})
| 148 | * @param {Object} options Contains message attributes and data |
| 149 | */ |
| 150 | handlePortMessage(options = {}) { |
| 151 | if (!this.#activePortMessages) { |
| 152 | return; |
| 153 | } |
| 154 | if (this._handlers.has(options.event)) { |
| 155 | const handler = this._handlers.get(options.event); |
| 156 | if (options._reply) { |
| 157 | // sender expects reply |
| 158 | Promise.resolve() |
| 159 | .then(() => handler.call(this, options)) |
| 160 | .then(result => this.emit('_reply', {result, _reply: options._reply})) |
| 161 | .catch(error => this.emit('_reply', {error: mapError(error), _reply: options._reply})); |
| 162 | } else { |
| 163 | // normal one way communication |
| 164 | handler.call(this, options); |
| 165 | } |
| 166 | } else if (options.event === '_reply') { |
| 167 | // we have received a reply |
| 168 | const replyHandler = this.#reply.get(options._reply); |
| 169 | this.#reply.delete(options._reply); |
| 170 | if (options.error) { |
| 171 | replyHandler.reject(options.error); |
| 172 | } else { |
| 173 | replyHandler.resolve(options.result); |
| 174 | } |
| 175 | } else { |
| 176 | console.log('Unknown event', options); |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | /** |
| 181 | * The new event handling style to asign a function to an event. |