A package which simply allows you to attach listeners to your variables.
$ npm i observedvar
const { ObservedVar } = require('observedvar');
// or (shorthand)
const { Ov } = require('observedvar');
const foo = new ObservedVar('defaultValue');
// or (shorthand with the right import)
const foo = new Ov('defaultValue');
foo.value = 'new value'
// or
foo.set('new value')
foo.value
// or
foo.get()
It return a listener object, use his id to unsubscribe.
const callback = (listener, newValue)=>{
console.log(`(listener ${listener.id}) Foo value changed, his value is now ${newValue}`)
if(conditionToDestroy) {
listener.destroy();
}
};
const fooListener = foo.subscribe(
callback,
isDirectlyDestroyedAfterBeingCalled // default is false
);
// shorthands
foo.sub(...)
foo.once(...) // equals to foo.sub(callback, true)
With the Ov variable
foo.unsubscribe(fooListener.id);
// shorthand
foo.unsub(...);
Or directly from the listener
fooListener.destroy();
You could use a listener to handle a fetch result. To prevent the following case
const fetchedData = new ObservedVar(null);
fetch(...).then(data=>{
fetchedData.value = data;
});
...
if(fetchedData===null) {
// supposing the data is fetching.
// so we need to subscribe a listener
fetchedData.subscribe(()=>handleData());
} else {
// supposing the data is already fetched.
// we don't need a listener
handleData();
}
Use once()
like that:
const fetchedData = new ObservedVar(null);
fetch(...).then(data=>{
fetchedData.value = data;
});
...
fetchedData.once(
handleData,
null // The value expected to subscribe a listener
);
It is returned when the method .subscribe(...)
is called, or within the callback
const fooListener = foo.sub(listener=>{
console.log(listener)
}, once);
console.log(fooListener)
// listener = fooListener = {
// once: false,
// id: 0,
// destroy: [Function: destroy],
// callback: [Function: callback]
// }
Full | Shorthand |
---|---|
new ObservedVar(defaultValue) |
new Ov(defaultValue) |
.subscribe(listener) |
.sub(listener) |
.unsubscribe(listenerId) |
.unsub(listenerId) |
.subscribe(listener, true) |
.once(listener) |