From 3e6342958b8839d46c9a4f68a60251fae86fc3c8 Mon Sep 17 00:00:00 2001 From: Felipe Duitama Date: Fri, 21 Jun 2019 17:37:37 -0500 Subject: [PATCH] doc: add example about emitter.emit in events documentation PR-URL: https://github.com/nodejs/node/pull/28374 Reviewed-By: James M Snell Reviewed-By: Rich Trott Reviewed-By: Yongsheng Zhang Reviewed-By: Ruben Bridgewater --- doc/api/events.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/doc/api/events.md b/doc/api/events.md index 1e41b10b8c7781..d102f8abcb72b8 100644 --- a/doc/api/events.md +++ b/doc/api/events.md @@ -307,6 +307,40 @@ to each. Returns `true` if the event had listeners, `false` otherwise. + +```js +const EventEmitter = require('events'); +const myEmitter = new EventEmitter(); + +// First listener +myEmitter.on('event', function firstListener() { + console.log('Helloooo! first listener'); +}); +// Second listener +myEmitter.on('event', function secondListener(arg1, arg2) { + console.log(`event with parameters ${arg1}, ${arg2} in second listener`); +}); +// Third listener +myEmitter.on('event', function thirdListener(...args) { + const parameters = args.join(', '); + console.log(`event with parameters ${parameters} in third listener`); +}); + +console.log(myEmitter.listeners('event')); + +myEmitter.emit('event', 1, 2, 3, 4, 5); + +// Prints: +// [ +// [Function: firstListener], +// [Function: secondListener], +// [Function: thirdListener] +// ] +// Helloooo! first listener +// event with parameters 1, 2 in second listener +// event with parameters 1, 2, 3, 4, 5 in third listener +``` + ### emitter.eventNames()