notify-js
A simplified global or private notification channel for values that happened in the past, and those that will happen in the future. Related blog entry.
API
There are 2 main methods such .that(type[, any1[, any2[, ...]]])
and .when(type[, callback])
,
plus 3 extra helpers such .drop(type, callback)
, .all(type, callback)
, and .new()
.
notify.that(type[, ...])
This method is useful to notify about a generic channel.
// whenever it happens ...navigatorgeolocation; // equivalent shortcut, will resolve// with the first argumentnavigatorgeolocation; // NodeJS API compatiblefs;
notify.that(type) and Promises
This method can also be used as middleware, passing along whatever first argument it receives.
// middlewareconnectToDb // resolves and returns the value ;
notify.when(type[, callback])
Usable both through callbacks or as Promise
, the .when
method asks for a channel and resolves it once available.
// using a callbacknotify; // Promise basednotify
It doesn't matter if .when
is used before or after a channel has been resolved, it will always pass along the last known resolved value.
// log on 'timer' channel (will log 123)notify; // resolves the channel with value 1notify; ;
Callback or Promise ?
If you are resolving older APIs like NodeJS require('fs').readFileSync
,
you probably want to use a callback because the resolution will pass along two arguments instead of one.
fs; notify;
As previously mentioned, you can still use the shortcut to resolve with all arguments once that happens.
fs;
notify.drop(type, callback)
Usable only for callbacks registered via notify.when(type, callback)
,
the .drop
method avoid triggering the channel in the immediate present or future.
{ console;} // wait for it to happennotify; // change your mindnotify; // whenever it happens// nothing will be loggednotify;
This method is particularly handy in conjunction of the notify.all(type, callback)
method.
notify.all(type, callback)
In case you'd like to react every time a channel is updated,
this method will register the callback
and invoke it with the latest resolution each time.
// each position changenavigatorgeolocation; // react to all position changesnotifyall 'geo:position' // tracker { console; };
Registered callbacks can be dropped through the notify.drop(type, callback)
method.
notify.new()
There are basically two ways to have a private notification channel:
- using a private
Symbol
as channel, like innotify.when(privateSymbol).then(log)
- create a local version of the notifier that will share nothing with the main one, like in
const notifyPVT = notify.new();
Which file ?
Browsers could use the minified version, otherwise there is a node module
which is also available via npm as npm install notify-js
.
Compatibility
This library is compatible with every JS engine since ES3, both browser and server,
but a Promise
polyfill might be needed to use Promise based patterns.