A StatefulEvt is an Evt stat keep a reference to the last value posted.
You can think of it as way to observe when a value is changed.
When you attach to a StatefulEvt the callback is immediately called with the current value (except with attachExtract and attachOnceExtract).
.state
Property type: T
reading the property gives the last event data posted. Setting the property (evt.state = data) is equivalent to calling .post(data).
.pipe(...)
Same as evt.pipe(...) but return a StatefulEvt. Be aware that the current state of the StatefulEvt must be matched by the operator ( if any ) when invoking .pipe(), elst an exception will be thrown.
Converting an Evt into a StatefulEvt
Basic example:
Concrete example:
onlyIfChanged operator
When using stetefull Evt is often usefull to have event posted only when the state value has changed. For that purpose you can pipe with the onlyIfChanged operator.
Concrete example:
If we take the previous example:
Now if we put the onlyIfChanged operator intor the mix:
import { Evt } from "evt";
// Evt that post whenever the window is resized window.addEventListener("resize", ...)
const evtResize = Evt.from(window, "resize");
// A statefulle evt with evtInnerWith state which is always the current value of
// window.innerSize.
const evtInnerWidth = evtResize
.toStatefull() // convert into a statefull evt with initial value set to unefined
.pipe(()=> [window.innerWidth]);
import { Evt } from "evt";
const evtInnerWidth = Evt.from(window, "resize")
.toStatefull()
.pipe(()=> [window.innerWidth]);
evtInnerWith.attach(innerWidth => {
// This callback will be called whenever the screen is resized
// including if only if the height has changed because
// window.addEventListener("resize", ()=> ...
// is the source event emitter.
});
import { Evt, onlyIfChanged } from "evt";
const evtInnerWidth = Evt.from(window, "resize")
.toStatefull()
.pipe(()=> [window.innerWidth])
// By default it compare object structure so { foo: 3 } is considered equal to
// an other object that would also be { foo: 3 }
.pipe(onlyIfChanged());
evtInnerWith.attach(innerWidth => {
// This callback will only be called whenever window.innerWidth
// actually changes.
});