Decouple your code with events
ON(name, fn) registers a listener, EMIT(name, a, b, c...) calls every listener with the given arguments, ONCE(name, fn) listens only for the first emit and OFF(name, fn) removes listeners. Events are in-process and synchronous. Use them to let a feature react to something (an order was paid) without the code that causes it knowing about the feature.
MAIN.audit = [];
ON('order.paid', function(order) {
MAIN.audit.push('paid ' + order.id);
});
ONCE('order.first', function(order) {
MAIN.audit.push('first ' + order.id);
});exports.install = function() {
ROUTE('POST /pay/{id}/', pay);
ROUTE('GET /audit/', audit);
};
function pay($) {
var order = { id: $.params.id };
EMIT('order.first', order);
EMIT('order.paid', order);
$.json({ ok: true });
}
function audit($) {
$.json(MAIN.audit);
}