# Decouple your code with events

> Emit and listen to application events with EMIT(), ON(), ONCE() and OFF() so modules do not call each other directly.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: en
Content-SHA256: 8f8c320254d43e4b540edf1b8cddaf71ba605cf9f39cb70fc33445a8edfc35ee
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

`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.

```js 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);
});
```

```js 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);
}
```
