Update createEventHub.md
This commit is contained in:
@ -2,7 +2,7 @@
|
||||
|
||||
Creates a pub/sub ([publish–subscribe](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.
|
||||
Create an empty `hub` property using `Object.create(null)` to create a truly empty object that does not inherit properties from `Object.prototype` (which would be resolved if the event name matched one of the properties).
|
||||
|
||||
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.
|
||||
@ -14,31 +14,26 @@ For `off`, use `Array.findIndex()` to find the index of the handler in the event
|
||||
|
||||
```js
|
||||
const createEventHub = () => ({
|
||||
hub: new Map(),
|
||||
hub: Object.create(null),
|
||||
emit(event, data) {
|
||||
(this.hub.get(event) || []).forEach(handler => handler(data));
|
||||
(this.hub[event] || []).forEach(handler => handler(data));
|
||||
},
|
||||
on(event, handler) {
|
||||
const handlers = this.hub.get(event);
|
||||
if (!handlers) this.hub.set(event, []);
|
||||
handlers.push(handler);
|
||||
if (!this.hub[event]) this.hub[event] = [];
|
||||
this.hub[event].push(handler);
|
||||
},
|
||||
off(event, handler) {
|
||||
const handlers = this.hub.get(event);
|
||||
const i = (handlers || []).findIndex(h => h === handler);
|
||||
if (i > -1) handlers.splice(i, 1);
|
||||
const i = (this.hub[event] || []).findIndex(h => h === handler);
|
||||
if (i > -1) this.hub[event].splice(i, 1);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
```js
|
||||
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(obj, fn); // subscribe a handler to listen for the object
|
||||
hub.emit('message', 'hello!'); // console logs 'hello!'
|
||||
hub.emit(obj, 'hello!'); // console logs 'hello!'
|
||||
hub.off('message', fn); // unsubscribe our handler from 'message', the obj event will still work
|
||||
hub.off('message', fn); // unsubscribe our handler from 'message'
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user