diff --git a/README.md b/README.md index ba45cf676..8300bbf91 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,7 @@ average(1, 2, 3); * [`bottomVisible`](#bottomvisible) * [`copyToClipboard`](#copytoclipboard-) * [`createElement`](#createelement) +* [`createEventHub`](#createeventhub-) * [`currentURL`](#currenturl) * [`detectDeviceType`](#detectdevicetype) * [`elementIsVisibleInViewport`](#elementisvisibleinviewport) @@ -1928,6 +1929,60 @@ console.log(el.className); // 'container'
[⬆ Back to top](#table-of-contents) +### createEventHub ![advanced](/advanced.svg) + +Creates a pub/sub ([publish–subscribe](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern)) event hub with `emit`, `on`, and `off` methods. + +Use `Object.create(null)` to create an empty `hub` object that does not inherit properties from `Object.prototype`. +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. +For `on`, create an array for the event if it does not yet exist, then use `Array.push()` to add the handler +to the array. +For `off`, use `Array.findIndex()` to find the index of the handler in the event array and remove it using `Array.splice()`. + +```js +const createEventHub = () => ({ + hub: Object.create(null), + emit(event, data) { + (this.hub[event] || []).forEach(handler => handler(data)); + }, + on(event, handler) { + if (!this.hub[event]) this.hub[event] = []; + this.hub[event].push(handler); + }, + off(event, handler) { + const i = (this.hub[event] || []).findIndex(h => h === handler); + if (i > -1) this.hub[event].splice(i, 1); + } +}); +``` + +
+Examples + +```js +const handler = data => console.log(data); +const hub = createEventHub(); +let increment = 0; + +// Subscribe: listen for different types of events +hub.on('message', handler); +hub.on('message', () => console.log('Message event fired')); +hub.on('increment', () => increment++); + +// Publish: emit events to invoke all handlers subscribed to them, passing the data to them as an argument +hub.emit('message', 'hello world'); // logs 'hello world' and 'Message event fired' +hub.emit('message', { hello: 'world' }); // logs the object and 'Message event fired' +hub.emit('increment'); // `increment` variable is now 1 + +// Unsubscribe: stop a specific handler from listening to the 'message' event +hub.off('message', handler); +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### currentURL Returns the current URL. diff --git a/docs/index.html b/docs/index.html index f0eda0fbc..6c279b4e6 100644 --- a/docs/index.html +++ b/docs/index.html @@ -40,7 +40,7 @@ },1700); } }, false); - }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Adapter

call

Given a key and a set of arguments, call them when given a context. Primarily useful in composition.

Use a closure to call a stored key with stored arguments.

const call = (key, ...args) => context => context[key](...args);
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Adapter

call

Given a key and a set of arguments, call them when given a context. Primarily useful in composition.

Use a closure to call a stored key with stored arguments.

const call = (key, ...args) => context => context[key](...args);
 
Promise.resolve([1, 2, 3])
   .then(call('map', x => 2 * x))
   .then(console.log); //[ 2, 4, 6 ]
@@ -369,6 +369,36 @@ Object.assig
   </div>`
 );
 console.log(el.className); // 'container'
+

createEventHubadvanced

Creates a pub/sub (publish–subscribe) event hub with emit, on, and off methods.

Use Object.create(null) to create an empty hub object that does not inherit properties from Object.prototype. 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. For on, create an array for the event if it does not yet exist, then use Array.push() to add the handler to the array. For off, use Array.findIndex() to find the index of the handler in the event array and remove it using Array.splice().

const createEventHub = () => ({
+  hub: Object.create(null),
+  emit(event, data) {
+    (this.hub[event] || []).forEach(handler => handler(data));
+  },
+  on(event, handler) {
+    if (!this.hub[event]) this.hub[event] = [];
+    this.hub[event].push(handler);
+  },
+  off(event, handler) {
+    const i = (this.hub[event] || []).findIndex(h => h === handler);
+    if (i > -1) this.hub[event].splice(i, 1);
+  }
+});
+
const handler = data => console.log(data);
+const hub = createEventHub();
+let increment = 0;
+
+// Subscribe: listen for different types of events
+hub.on('message', handler);
+hub.on('message', () => console.log('Message event fired'));
+hub.on('increment', () => increment++);
+
+// Publish: emit events to invoke all handlers subscribed to them, passing the data to them as an argument
+hub.emit('message', 'hello world'); // logs 'hello world' and 'Message event fired'
+hub.emit('message', { hello: 'world' }); // logs the object and 'Message event fired'
+hub.emit('increment'); // `increment` variable is now 1
+
+// Unsubscribe: stop a specific handler from listening to the 'message' event
+hub.off('message', handler);
 

currentURL

Returns the current URL.

Use window.location.href to get current URL.

const currentURL = () => window.location.href;
 
currentURL(); // 'https://google.com'
 

detectDeviceType

Detects wether the website is being opened in a mobile device or a desktop/laptop.

Use a regular expression to test the navigator.userAgent property to figure out if the device is a mobile device or a desktop/laptop.

const detectDeviceType = () =>
diff --git a/snippets/createEventHub.md b/snippets/createEventHub.md
index de2b0139e..5b11f4530 100644
--- a/snippets/createEventHub.md
+++ b/snippets/createEventHub.md
@@ -8,7 +8,7 @@ For `on`, create an array for the event if it does not yet exist, then use `Arra
 to the array.
 For `off`, use `Array.findIndex()` to find the index of the handler in the event array and remove it using `Array.splice()`.
 
-```js
+```js
 const createEventHub = () => ({
   hub: Object.create(null),
   emit(event, data) {
@@ -25,7 +25,7 @@ const createEventHub = () => ({
 });
 ```
 
-```js
+```js
 const handler = data => console.log(data);
 const hub = createEventHub();
 let increment = 0;
@@ -41,5 +41,5 @@ hub.emit('message', { hello: 'world' }); // logs the object and 'Message event f
 hub.emit('increment'); // `increment` variable is now 1
 
 // Unsubscribe: stop a specific handler from listening to the 'message' event
-hub.off('message', handler); 
+hub.off('message', handler);
 ```
diff --git a/tag_database b/tag_database
index 7330da5ca..a1a0c2388 100644
--- a/tag_database
+++ b/tag_database
@@ -20,9 +20,9 @@ copyToClipboard:browser,string,advanced
 countOccurrences:array
 countVowels:string
 createElement:browser,utility
+createEventHub:browser,event,advanced
 currentURL:browser,url
 curry:function,recursion
-createEventHub:browser,event,advanced
 deepFlatten:array,recursion
 defer:function
 detectDeviceType:browser