Use Map instead

This commit is contained in:
atomiks
2018-01-09 05:44:23 +11:00
committed by GitHub
parent 489c524a0d
commit 5de60aec57

View File

@ -2,6 +2,8 @@
Creates a pub/sub ([publishsubscribe](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern)) event hub with `emit`, `on`, and `off` methods. Creates a pub/sub ([publishsubscribe](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern)) event hub with `emit`, `on`, and `off` methods.
Instantiate a new `Map` object to allow any event type (including objects) to be the key, and also so object prototype property names are not resolved.
For `emit`, resolve the array of handlers based on the `event` argument and then run For `emit`, resolve the array of handlers based on the `event` argument and then run
each one with `Array.forEach()` by passing in the data as an argument. each one with `Array.forEach()` by passing in the data as an argument.
@ -12,25 +14,29 @@ For `off`, use `Array.findIndex()` to find the index of the handler in the event
```js ```js
const createEventHub = () => ({ const createEventHub = () => ({
hub: {}, hub: new Map(),
emit(event, data) { emit(event, data) {
(this.hub[event] || []).forEach(handler => handler(data)); (this.hub.get(event) || []).forEach(handler => handler(data));
}, },
on(event, handler) { on(event, handler) {
if (!this.hub[event]) this.hub[event] = []; if (!this.hub.get(event)) this.hub.set(event, []);
this.hub[event].push(handler); this.hub.get(event).push(handler);
}, },
off(event, handler) { off(event, handler) {
const i = (this.hub[event] || []).findIndex(h => h === handler); const i = (this.hub.get(event) || []).findIndex(h => h === handler);
if (i > -1) this.hub[event].splice(i, 1); if (i > -1) this.hub.get(event).splice(i, 1);
} }
}); });
``` ```
```js ```js
const hub = createEventHub();
const fn = data => console.log(data); const fn = data => console.log(data);
const obj = {};
const hub = createEventHub();
hub.on('message', fn); // subscribe a handler to listen for 'message' events hub.on('message', fn); // subscribe a handler to listen for 'message' events
hub.on(obj, fn); // subscribe a handler to listen for the object
hub.emit('message', 'hello!'); // console logs 'hello!' hub.emit('message', 'hello!'); // console logs 'hello!'
hub.off('message', fn); // unsubscribe our handler from 'message' hub.emit(obj, 'hello!'); // console logs 'hello'
hub.off('message', fn); // unsubscribe our handler from 'message', the obj event will still work
``` ```