This is an experiment to find out whether entire programs can be written using pub/sub and what is required to make that possible. It is running on Node and in the browser (using nomo.js). It should allow implementations to change from synchronous to asynchronous without the need to change one of the callers. It should also allow to intercept or hook into exising behavior.
The first implementation was getting too complicated and I've leared a lot on the way. Therefore I'm starting again from scratch which means this is all quite early, buggy and incomplete. Feel free to join or provide feedback. If you think all this is an utterly stupid idea, talk to the hand.
Pub/sub is the core concept in hub.js. Event names are dot separated identifiers.
hub.on('hello.world', function () { /* ... */ });
hub.emit('hello.world');
Listeners can take arguments and either return a value or expect a callback as the last argument that receives the return value. The following two listeners behave identically:
hub.on('greet', function (who) {
return 'Hello ' + who;
});
hub.on('greet', function (who, callback) {
callback(null, 'Hello ' + who);
});
Although there are two ways to return values, they can only be received via a callback. This allows listener implementations to change from synchronous to asynchronous without changing any of the "callers".
hub.emit('greet', 'Hub', function (err, greeting) { /* ... */ });
If multiple listeners are registered for the same event, a decision has to be made about how to deal with multiple return values. By default, the last non-undefined value is returned. There are a number of different strategies available, e.g. MERGE, CONCAT, MIN, MAX ... It is also possible to provide custom strategies. The strategy has to be the last argument before the callback.
hub.emit('greet', 'Hub', hub.CONCAT, function (err, greeting) { /* ... */ });