Skip to content

Commit 461ec0d

Browse files
Merge pull request #1595 from johannesschobel/docs/events
[Docs]: Improve Events
2 parents 8fcea8a + e538545 commit 461ec0d

File tree

1 file changed

+30
-18
lines changed

1 file changed

+30
-18
lines changed

content/techniques/events.md

Lines changed: 30 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,29 @@ EventEmitterModule.forRoot({
5050
});
5151
```
5252

53-
#### Event listeners
53+
#### Dispatching Events
54+
55+
To dispatch (i.e., fire) an event, first inject `EventEmitter2` using standard constructor injection:
56+
57+
```typescript
58+
constructor(private eventEmitter: EventEmitter2) {}
59+
```
60+
61+
> info **Hint** Import the `EventEmitter2` from the `@nestjs/event-emitter` package.
62+
63+
Then use it in a class as follows:
64+
65+
```typescript
66+
this.eventEmitter.emit(
67+
'order.created',
68+
new OrderCreatedEvent({
69+
orderId: 1,
70+
payload: {},
71+
}),
72+
);
73+
```
74+
75+
#### Listening to Events
5476

5577
To declare an event listener, decorate a method with the `@OnEvent()` decorator preceding the method definition containing the code to be executed, as follows:
5678

@@ -79,26 +101,16 @@ handleOrderEvents(payload: OrderCreatedEvent | OrderRemovedEvent | OrderUpdatedE
79101
}
80102
```
81103

82-
#### Dispatching events
104+
Note that such a wildcard only applies to one block. The argument `order.*` will match, for example, the events `order.created` and `order.shipped` but not `order.delayed.out_of_stock`. In order to listen to such events,
105+
use the `multilevel wildcard` pattern (i.e, `**`), described in the `EventEmitter2` [documentation](https://github.com/EventEmitter2/EventEmitter2#multi-level-wildcards).
83106

84-
To dispatch an event, first inject `EventEmitter2` using standard constructor injection:
107+
With this pattern, you can, for example, create an event listener that catches all events.
85108

86109
```typescript
87-
constructor(private eventEmitter: EventEmitter2) {}
88-
```
89-
90-
> info **Hint** Import the `EventEmitter2` from the `@nestjs/event-emitter` package.
91-
92-
Then use it in a class as follows.
93-
94-
```typescript
95-
this.eventEmitter.emit(
96-
'order.created',
97-
new OrderCreatedEvent({
98-
orderId: 1,
99-
payload: {},
100-
}),
101-
);
110+
@OnEvent('**')
111+
handleEverything(payload: any) {
112+
// handle and process an event
113+
}
102114
```
103115

104116
> info **Hint** `EventEmitter2` class provides several useful methods for interacting with events, like `waitFor` and `onAny`. You can read more about them [here](https://github.com/EventEmitter2/EventEmitter2).

0 commit comments

Comments
 (0)