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]);
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:
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.
});
Now if we put the onlyIfChanged operator intor the mix:
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.
});
To prevent a StatefulEvt to be posted by parts of the code that is not supposed to StatefulEvt can be exposed as StatefulReadonlyEvt.
import { StatefulEvt, StatefulReadonlyEvt } from "evt";
//Return an event that post every second.
function generateEvtTick(delay: number): StatefulReadonlyEvt<number> {
const evtTick= new StatefulEvt(0);
setInterval(()=> evtTick.state++, delay);
retrun evtTick;
}
const evtTick= generateTick(1000);
evtTick.state++; // TS ERROR
evtTick.post(2); // TS ERROR
.toStateless([ctx])
Return a stateless copy of the Evt.
import { Evt } from "evt";
const evtText= Evt.create("foo");
//x is Evt<string>
const x= evtText.toStateless();
evt.toStateless() is equivalent to Evt.prototype.pipe.call(evt)
Same as 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.