From 42fa5e8d4de1242cf5fd1ad3f1fd97639ce673d5 Mon Sep 17 00:00:00 2001 From: DarkWiiPlayer Date: Sat, 2 Jul 2022 10:55:38 +0200 Subject: [PATCH] Document speaker class --- index.html | 18 ++++++++++ page/speaker.html | 88 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 page/speaker.html diff --git a/index.html b/index.html index 97071a8..e75451a 100644 --- a/index.html +++ b/index.html @@ -15,6 +15,8 @@

A collection of JavaScript modules to make front-end easier.

+

+

@@ -81,6 +83,22 @@

+
+

Speaker

+

+ Publish and subscribe to messages, relayed via micro-tasks. + Read More + + + const speaker = new Speaker() + speaker.listen((...args) => console.log(...args)) + speaker.speak("First", "second", "third") + + + No, this has nothing to do with playing audio. +

+
+

Debounce

diff --git a/page/speaker.html b/page/speaker.html new file mode 100644 index 0000000..254e93b --- /dev/null +++ b/page/speaker.html @@ -0,0 +1,88 @@ + + + + + + + + + +Module Index + +

speaker.js

+ +import {Speaker} from 'speaker.js' + +
+

Description

+

+ A publish/subscribe helper class that uses micro-tasks to relay messages to many subscribers. +

+
+ +
+

Example

+ + + const speaker = new Speaker() + speaker.listen(message => { document.title = message }) + speaker.listen(message => { console.log(`Message received: ${message}`) }) + + speaker.speak("New page title") + console.log("This line runs before any of the callbacks") + + +

+ Note that the callbacks don't run immediately. + They are scheduled to a micro-task to be called later on. +

+ +
+ +
+

Methods

+
+
new Speaker(...initial) : Speaker
+
+ Constructs a new speaker. + All arguments passed to the constructor will be retained and returned + by any call to listen before the first time speak + is called. +
+ +
Speaker.listen(callback : (...args) => undefined) : [...args]
+
+ Registers a callback to be called on every new message. + Returns an array containing the retained arguments of the last message. +
+ +
Speaker.speak(...args)
+
+ Relays a message of zero or more arguments to all registered callbacks. + As mentioned above, callbacks will not be called immediately, but scheduled in a new micro-task. + The arguments are retained until speak is called again. +
+ +
Speaker.forget(callback)
+
+ Removes a single callback function from its list of callbacks. +
+ +
Speaker.silence()
+
+ Clears the list of callbacks completely. +
+
+
+ +
+

Immediate Speaker

+

+ Additionally, the module exposts the ImmediateSpeaker class, + which does the exact same as a normal speaker, + but executes its callbacks immediately instead of scheduling a micro-task. +

+

+ The API is the exact same as a normal Speaker. +

+