ForgeTotal.js 5
en

Total.js 5

Decouple your code with events

Total.js 5 · total5@0.0.19 eventsarchitecture Executed against Total.js 5

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.

definitions/audit.js
MAIN.audit = [];

ON('order.paid', function(order) {
	MAIN.audit.push('paid ' + order.id);
});

ONCE('order.first', function(order) {
	MAIN.audit.push('first ' + order.id);
});
controllers/orders.js
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);
}