@soil/arch
Version:
Architectural constructs for web applications.
51 lines • 1.67 kB
JavaScript
/**
* Type-safe event mini-bus, or publisher/subscriber system. Useful for
* communicating distant components.
*/
export function chan() {
var listeners = [];
/**
* Unsubscribe a listener from the channel.
*/
function unsub(listener) {
listeners = listeners.filter(function (l) { return l !== listener; });
}
return {
/**
* Subscribe a listener to the channel. A function is returned which can
* be called to unsubscribe that same listener. An optional second
* argument may be passed to specify the maximum number of times the
* listener will be notified before automatically unsubscribing it.
*/
sub: function (listener, times) {
var timesIsDefined = times !== undefined;
var listenerWrapper = function (msg) {
if (timesIsDefined && --times === 0) {
unsub(listenerWrapper);
}
listener(msg);
};
listeners.push(listenerWrapper);
return function () { return unsub(listenerWrapper); };
},
/**
* Send an event to all listeners, with a payload.
*/
pub: function (msg) {
listeners.slice().forEach(function (l) { return l(msg); });
},
/**
* Return the number of listeners on the channel.
*/
get size() {
return listeners.length;
},
/**
* Unsubscribe all listeners from the channel.
*/
clear: function () {
listeners.length = 0;
}
};
}
//# sourceMappingURL=chan.js.map