- Like a normal object, except you can register callbacks for property changes.
- Read More
-
-
-
-
Code Sample:
-
- import listener from 'listener.js'
-
- const user = listener({name: "John Doe"})
- user.listen('name', value => console.warn(`User name has changed to ${value}`))
-
-
-
-
-
-
Speaker
-
- Publish and subscribe to messages, relayed via micro-tasks.
- Read More
+ Utility class to monitor state changes on an object using a Proxy and events.
+ Changes are batched and processed in a microtask.
+ Read More
- const speaker = new Speaker()
- speaker.listen((...args) => console.log(...args))
- speaker.speak("First", "second", "third")
+ const state = new State()
+ speaker.meepChanged = value => console.log(`meep ${value}`)
+ state.proxy.meep = "Heat from fire"
+ state.proxy.meep = "Fire from heat"
+ state.proxy.meep = "moop"
+ // outputs: "meep moop"
No, this has nothing to do with playing audio.
diff --git a/listener.js b/listener.js
index d2764b3..0872ade 100644
--- a/listener.js
+++ b/listener.js
@@ -9,6 +9,7 @@ Example:
*/
const registry = new WeakMap()
+
const listener = (target={}) => {
const callbacks = new Map()
const methods = Object.create(null)
@@ -16,7 +17,7 @@ const listener = (target={}) => {
const callback = once
? (...args) => { this.forget(name, callback); return fn(...args) }
: fn
- let set = callbacks.get(name) ?? new Set()
+ const set = callbacks.get(name) ?? new Set()
callbacks.set(name, set)
set.add(callback)
return this
@@ -29,13 +30,13 @@ const listener = (target={}) => {
return callbacks.delete(name)
}
}
- let proxy = new Proxy(target, {
+ const proxy = new Proxy(target, {
set: (target, prop, value) => {
if (callbacks.has(null)) callbacks.get(null).forEach(callback => callback(value, target[prop], prop))
if (callbacks.has(prop)) callbacks.get(prop).forEach(callback => callback(value, target[prop], prop))
return Reflect.set(target, prop, value)
},
- get: (target, prop, value) => prop in methods
+ get: (target, prop, _value) => prop in methods
? methods[prop]
: target[prop]
})
diff --git a/page/state.html b/page/state.html
new file mode 100644
index 0000000..bf6c094
--- /dev/null
+++ b/page/state.html
@@ -0,0 +1,91 @@
+
+
+
+
+
+
+
+
+Module Index
+
+
listener.js
+
+import {State} from 'state.js'
+
+
+
Description
+
+ State objects emit an event whenever a property gets written to on their associated Proxy.
+
+
+
+ By default, state changes are only queued up and processed in a microtask, allowing for batch-processing.
+ This means that for repeated changes to the same property, the user can decide to process all the changes in one go or even discard everything but the last value of each property.
+ That way one can easily avoid some types of unnecessary redraws, network requests, etc.
+
+
+
+ To make code more readable, the constructor defaults to adding an event listener that checks for a method called [prop]Changed in the state object, and calls it with the new value. This behaviour can be disabled by setting the methods option to false.
+
+
+
+ The state object also has a getter and setter pair for the `state` attribute, which simply accesses this same attribute on the proxy object.
+ This is simply a convenience feature to save some typing on single-variable states.
+
+
+
+
+
Options
+
+
+
defer
+
Set to false to disable defered change processing. This will emit a new event every time something changes, even if it's about to be changed again in the next line.
+
methods
+
Set to false to disable the default event listener that attempts to call a [prop]Changed method on the state object.
+
+
+
+
+
+
Examples
+
+
+ A simple counter state that prints a new count to the console every time it gets updated.
+
+ This example uses an event listener instead to get notified of all property changes.
+ Collecting changes into a map is an easy way of de-duplicating their values and keeping only the last one.
+
+
+
+ const state = new State({}, {methods: false})
+
+ state.addEventListener("change", event => {
+ console.log(`There were ${event.changes.length} changes.`)
+ new Map(event.changes).forEach((value, prop) => {
+ console.log(`Final vaue of ${prop}: ${value}`)
+ })
+ })
+
+ state.proxy.foo = "foo 1"
+ state.proxy.foo = "foo 2"
+ state.proxy.bar = "bar 1"
+ state.proxy.foo = "foo 3"
+ state.proxy.bar = "bar 2"
+
+ // There were 5 changes.
+ // Final vaue of foo: foo 3
+ // Final vaue of bar: bar 2
+
+
diff --git a/readme.md b/readme.md
index 1997312..003c444 100644
--- a/readme.md
+++ b/readme.md
@@ -24,13 +24,22 @@ support inheriting from other classes for extending builtin elements.
Generate CSS from JS objects. Yes, you can generate CSS from JSON now. Or from
YAML. Or from whatever you want, really.
+## State
+
+Combines both Listener and Speaker into one convenient class that batches and
+defers changes by default.
+
## Listener
+(Deprecated; use `State` instead)
+
A proxy object that fires a callback when certain (or all) properties are
changed.
## Speaker
+(Deprecated; use `State` instead)
+
Simple messaging helper that uses microtasks by default.
## Debounce
diff --git a/speaker.js b/speaker.js
index 2066689..6c5a370 100644
--- a/speaker.js
+++ b/speaker.js
@@ -15,8 +15,8 @@ export class Speaker {
speak(...args) {
if (!this._scheduled.length) {
queueMicrotask(() => {
- for (let args of this._scheduled) {
- for (let callback of this._callbacks) {
+ for (const args of this._scheduled) {
+ for (const callback of this._callbacks) {
callback(...args)
}
this._retain = args
@@ -28,7 +28,7 @@ export class Speaker {
}
forget(callback) {
- this._callbacks.delete(callbacks)
+ this._callbacks.delete(callback)
}
silence() {
@@ -38,7 +38,7 @@ export class Speaker {
export class ImmediateSpeaker extends Speaker {
speak(...args) {
- for (let callback of this._callbacks) {
+ for (const callback of this._callbacks) {
callback(...args)
}
this._retain = args
diff --git a/state.js b/state.js
new file mode 100644
index 0000000..3138a54
--- /dev/null
+++ b/state.js
@@ -0,0 +1,53 @@
+export class ChangeEvent extends Event {
+ constructor(...changes) {
+ super('change')
+ this.changes = changes
+ }
+}
+
+export class State extends EventTarget {
+ #target
+ #options
+ #queue
+ constructor(target={}, options={}) {
+ super()
+ this.#options = options
+ this.#target = target
+ this.proxy = new Proxy(target, {
+ set: (_target, prop, value) => { this.set(prop, value); return true },
+ get: (target, prop) => target[prop],
+ })
+
+ this.addEventListener
+
+ if (options.methods ?? true) {
+ this.addEventListener("change", ({changes}) => {
+ new Map(changes).forEach((value, prop) => {
+ if (`${prop}Changed` in this) this[`${prop}Changed`](value)
+ })
+ })
+ }
+ }
+
+ set state(value) { this.proxy.state = value }
+ get state() { return this.proxy.state }
+
+ set(prop, value) {
+ if (this.#options.defer ?? true) {
+ if (!this.#queue) {
+ this.#queue = []
+ queueMicrotask(() => {
+ this.dispatchEvent(new ChangeEvent(...this.#queue))
+ this.#queue = undefined
+ })
+ }
+ this.#queue.push([prop, value])
+ this.#target[prop] = value
+ } else {
+ this.#target[prop] = value
+ this.dispatchEvent(new ChangeEvent([prop, value]))
+ }
+ }
+}
+
+export default State