refactor(api): move event's once to its own function (#1276)

This commit is contained in:
Lucas Fernandes Nogueira 2021-02-23 21:31:15 -03:00 committed by GitHub
parent 8a120683b6
commit 372036ce20
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 51 additions and 15 deletions

View File

@ -0,0 +1,5 @@
---
"tauri-api": minor
---
The event listener `once` kind was moved to a dedicated function.

View File

@ -4,5 +4,5 @@ async function emit(event: string, payload?: string): Promise<void> {
return emitEvent(event, undefined, payload)
}
export { listen } from './helpers/event'
export { listen, once } from './helpers/event'
export { emit }

View File

@ -7,16 +7,10 @@ export interface Event<T> {
export type EventCallback<T> = (event: Event<T>) => void
/**
* listen to an event from the backend
*
* @param event the event name
* @param handler the event handler callback
*/
async function listen<T>(
async function _listen<T>(
event: string,
handler: EventCallback<T>,
once = false
once: boolean
): Promise<void> {
await invoke({
__tauriModule: 'Event',
@ -29,6 +23,32 @@ async function listen<T>(
})
}
/**
* listen to an event from the backend
*
* @param event the event name
* @param handler the event handler callback
*/
async function listen<T>(
event: string,
handler: EventCallback<T>
): Promise<void> {
return _listen(event, handler, false)
}
/**
* listen to an one-off event from the backend
*
* @param event the event name
* @param handler the event handler callback
*/
async function once<T>(
event: string,
handler: EventCallback<T>
): Promise<void> {
return _listen(event, handler, true)
}
/**
* emits an event to the backend
*
@ -51,4 +71,4 @@ async function emit(
})
}
export { listen, emit }
export { listen, once, emit }

View File

@ -1,5 +1,5 @@
import { invoke } from './tauri'
import { EventCallback, emit, listen } from './helpers/event'
import { EventCallback, emit, listen, once } from './helpers/event'
interface WindowDef {
label: string
@ -33,14 +33,25 @@ class TauriWindow {
*
* @param event the event name
* @param handler the event handler callback
* @param once unlisten after the first trigger if true
*/
async listen<T>(
event: string,
handler: EventCallback<T>,
once = false
handler: EventCallback<T>
): Promise<void> {
return listen(event, handler, once)
return listen(event, handler)
}
/**
* Listen to an one-off event emitted by the webview
*
* @param event the event name
* @param handler the event handler callback
*/
async once<T>(
event: string,
handler: EventCallback<T>
): Promise<void> {
return once(event, handler)
}
/**