fluids
This library is a tiny glue layer for observable events.
- Create a tree of observable values
- Let parent nodes send arbitrary events to children (for maximum flexibility)
- Stay small yet provide helpers for easier integration
Observe a value
Any object can be observed, but FluidValue
objects have strongly typed
events. Observed objects are basically event emitters whose listeners
receive every event, and they typically represent a single value.
To start observing:
import { addFluidObserver } from 'fluids'
let observer = addFluidObserver(target, (event) => {
console.log(event)
})
observer = addFluidObserver(target, {
eventObserved(event) {
console.log(event)
},
})
To stop observing:
import { removeFluidObserver } from 'fluids'
removeFluidObserver(target, observer)
Create an observed object
You can extend the FluidValue
class for automatic TypeScript support with
fluids
-compatible libraries.
import { FluidValue, FluidObservable, callFluidObservers } from 'fluids'
type RefEvent<T> = { type: 'change'; value: T; parent: Ref<T> }
interface Ref<T> extends FluidObservable<RefEvent<T>> {}
class Ref<T> extends FluidValue<T> {
private _current: T
constructor(initialValue: T) {
super(() => this._current)
this._current = initialValue
}
get current() {
return this._current
}
set current(value: T) {
this._current = value
callFluidObservers(this, {
type: 'change',
value,
parent: this,
})
}
protected observerAdded(count: number) {
if (count == 1) {
}
}
protected observerRemoved(count: number) {
if (count == 0) {
}
}
}
If extending FluidValue
isn't an option, you can outfit an object or
prototype with the setFluidGetter
function:
import { setFluidGetter, callFluidObservers } from 'fluids'
let { current } = ref
let get = () => current
setFluidGetter(ref, get)
Object.defineProperty(ref, 'current', {
get,
set(value) {
current = value
callFluidObservers(ref, {
type: 'change',
value,
parent: ref,
})
},
})
For libraries
The remaining functions are useful when making a fluids
-compatible library.
import {
hasFluidValue,
getFluidValue,
getFluidObservers,
callFluidObserver,
} from 'fluids'
hasFluidValue(target)
getFluidValue(target)
getFluidObservers(target)
callFluidObserver(observer, event)