Skip to content

Commit e10786c

Browse files
committed
chore(readme): add documentation about nested events
1 parent 76b61aa commit e10786c

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

README.md

+52
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,58 @@ export const Parent = _Parent & WithEventsDummyType(ParentEvents);
7070
```
7171
This type (`Parent`) is what should be exported and used by other code (_not_ `_Parent`).
7272

73+
### Specifying Paths to Nested Event Locations with `AddEvents`
74+
75+
To accommodate complex class structures where events are organized within nested objects, the `AddEvents` utility allows specifying a path to these nested event locations. This feature enhances the ability to manage events in a structured manner within classes.
76+
77+
#### Enhancing Classes with Nested Events
78+
79+
For classes where events are nested within an object, you can specify the path to these nested events when enhancing your class. This approach helps maintain organized and encapsulated event structures.
80+
81+
**Example: Setting Up Nested Events**
82+
83+
Consider a class with events nested under a property called `eventsContainer`:
84+
85+
```typescript
86+
// Define an interface
87+
interface NestedEvents {
88+
eventOne: TypedEvent<() => void>;
89+
}
90+
91+
// Define a class with nested events
92+
class _Nested {
93+
eventsContainer = {
94+
eventOne: new TypedEvent<() => void>()
95+
};
96+
}
97+
98+
// Enhance the class by specifying the path to nested events
99+
const Nested = AddEvents<typeof _Nested, NestedEvents>(_Nested, 'eventsContainer');
100+
101+
// Create an instance and attach event listeners
102+
const instance = new Nested();
103+
instance.on('eventOne', () => console.log('Ready event triggered'));
104+
instance.eventsContainer.eventOne.emit();
105+
```
106+
107+
#### Error Handling for Incorrect Paths
108+
109+
If an incorrect path is provided, the utility throws an error. This ensures your event paths are correctly configured and provides immediate feedback for debugging.
110+
111+
**Example: Incorrect Path Configuration**
112+
113+
Here’s how errors are managed when an incorrect path is specified:
114+
115+
```typescript
116+
try {
117+
const InvalidClass = AddEvents<typeof Nested, NestedEvents>(Nested, 'incorrectPath');
118+
const wrongInstance = new InvalidClass();
119+
wrongInstance.on('eventOne', () => console.log('This will never run'));
120+
} catch (error) {
121+
console.error(error); // Outputs: Error: Event "incorrectPath.eventOne" is not defined
122+
}
123+
```
124+
73125

74126
## FAQ
75127
##### _Rather than requiring constraints on the type `U` in AddEvents via documentation, why not express them in the type system?_

0 commit comments

Comments
 (0)