Channeljs aims to offer a easy-to-use and flexible Observer pattern implementation.
Create a Channel, or get it if already exists.
// Somewhere, subscribe to the "mult"
// topic of the "math" channel
Channel.get('math').sub('mult', function() {
var args = [].slice.call(arguments, 0);
return args.reduce(function(el, acc) {
return acc * el;
}, 1);
});then elsewhere
var mult = Channel.get('math').pub('mult', [2, 3, 5, 7, 11, 13, 17]);
console.log(mult) // 510510so the flow seem to be
- subscribe to a topic passing as second parameter a function that will receive all parameters passed when publishing, the function will most likely return a result.
- get that result calling publish to a topic passing all parameters needed for the subscriber to be able to calculate and return the result.
...there is something more:
-
since there could be more subscribers to the same topic, in that case publish will return an array of results, each one corresponding to the result returned from the relative subscriber (subscription order).
-
it's possible to do the opposite, allowing for example a `late` subscriber to be informed at subscription time of a past publishing on a topic.
-
couple of more functions:
once(sub),enable,disable,unsub(one, more,or all topics) andreset
Once the script has been imported in the browser, or required in Your script (I assume required as Channeljs), there are two static functions available:
const myChannels = Channeljs.getAllChannels({enabledStatus <boolean>});Returns an object literal containing all existing Channels, optionally can be passed a boolean value which enables a filter, when true it will return only all enabled Channels, when false only disabled ones.
const uxEvents = Channeljs.get('ux');Creates, if not already existing, an instance of Channel indexed as ux and returns it. Now we can use it.
uxEvents.pub('cartUpdated', articles)Publishes parameters on one or more topics.
uxEvents.sub('cartUpdated', function () {
var articles = [].slice.call(arguments, 0);
})Registers a listener to a particular topic on the channel; the subscribing function will receive all parameters passed in an array as second parameter at pub call:
ch.pub('bePolite', ['Hello', 'World', '!'])
...
ch.sub('bePolite', function (a, b, c) {
console.log(`${a} ${b} ${c}`) // Hello World !
}, true) // true here enables retroActivityThe retroActive parameter allows the subcriber to be executed immediately for all relevant past published events.
Removes the subscriber from the topic
Exactly as sub but once, not retroactivable.
Enables a channel
Disables a channel
for the moment .... not to be continued