Skip to content

Commit

Permalink
feat(ui): Add type support for EventBus class (#15759)
Browse files Browse the repository at this point in the history
* feat(ui): Add type support for EventBus class

* feat(docs): Add type support for EventBus class

* Update event-bus-util.md

---------

Co-authored-by: Razvan Stoenescu <razvan.stoenescu@gmail.com>
  • Loading branch information
marvin-wtt and rstoenescu committed Apr 27, 2023
1 parent dd8f8d8 commit 8d8fa8b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
14 changes: 14 additions & 0 deletions docs/src/pages/quasar-utils/event-bus-util.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,20 @@ bus.on('some-event', (arg1, arg2, arg3) => {
bus.emit('some-event', 'arg1 value', 'arg2 value', 'arg3 value')
```

If using Typescript, then events can also be typed strictly:

```js
// Quasar v2.11.11+
import { EventBus } from 'quasar'

const bus = new EventBus<{
'some-event': (arg1: string, arg2: string, arg3: string) => void;
'other': (arg: boolean) => void;
}>()

bus.emit('some-event', 'arg1 value', 'arg2 value', 'arg3 value')
```

### Convenience usage

Create a file in your app where you instantiate and export the new event bus then import and use it throughout your app.
Expand Down
14 changes: 9 additions & 5 deletions ui/types/utils.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,15 @@ export function setCssVar(
element?: Element
): void;

export class EventBus {
on(event: string, callback: Function, ctx?: any): this;
once(event: string, callback: Function, ctx?: any): this;
emit(event: string, ...args: any[]): this;
off(event: string, callback?: Function): this;
interface Callbacks {
[key: string]: (...args: any[]) => void;
}

export class EventBus<T extends Callbacks> {
on<K extends keyof T>(event: K, callback: T[K], ctx?: any): this;
once<K extends keyof T>(event: K, callback: T[K], ctx?: any): this;
emit<K extends keyof T>(event: K, ...args: Parameters<T[K]>): this;
off<K extends keyof T>(event: K, callback: T[K]): this;
}

interface CreateMetaMixinContext extends ComponentPublicInstance {
Expand Down

0 comments on commit 8d8fa8b

Please sign in to comment.