Node.js › Events & EventEmitter

How would you implement a custom event that carries multiple pieces of data, and what's the convention for structuring the emitted payload?

Advanced

Answer

emit() can pass any number of additional arguments after the event name, which are delivered as separate arguments to the listener function -- but the common and generally recommended convention, especially as an event's data grows more complex over time, is to emit a single structured object payload rather than several positional arguments, since adding a new piece of data later to a positional-argument approach breaks every existing listener's function signature, whereas adding a new property to an object payload doesn't.
// Fragile: adding a new positional argument later breaks existing listeners
this.emit('orderPlaced', orderId, userId, total);

// More maintainable: a single structured payload, extensible without breaking existing listeners
this.emit('orderPlaced', { orderId, userId, total, timestamp: Date.now() });

order.on('orderPlaced', (event) => {
  console.log(event.orderId, event.total);
});
Real-world example A payment-processing class initially emitted 'paymentCompleted' with three positional arguments, but after needing to add a fourth piece of data (a transaction fee) without breaking several existing listeners already deployed elsewhere in the codebase, the team refactored to emit a single object payload going forward, making future additions backward-compatible by default.

Common follow-ups: How would you version an event's payload shape if you need to make a genuinely breaking change to it eventually?;What's the tradeoff of a single generic 'event' name carrying a 'type' field inside its payload, versus many specifically-named events?