event.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { invokeTauriCommand } from './tauri.js';
  2. import { transformCallback } from '../tauri.js';
  3. // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
  4. // SPDX-License-Identifier: Apache-2.0
  5. // SPDX-License-Identifier: MIT
  6. /**
  7. * Unregister the event listener associated with the given name and id.
  8. *
  9. * @ignore
  10. * @param event The event name
  11. * @param eventId Event identifier
  12. * @returns
  13. */
  14. async function _unlisten(event, eventId) {
  15. return invokeTauriCommand({
  16. __tauriModule: 'Event',
  17. message: {
  18. cmd: 'unlisten',
  19. event,
  20. eventId
  21. }
  22. });
  23. }
  24. /**
  25. * Emits an event to the backend.
  26. *
  27. * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
  28. * @param [windowLabel] The label of the window to which the event is sent, if null/undefined the event will be sent to all windows
  29. * @param [payload] Event payload
  30. * @returns
  31. */
  32. async function emit(event, windowLabel, payload) {
  33. await invokeTauriCommand({
  34. __tauriModule: 'Event',
  35. message: {
  36. cmd: 'emit',
  37. event,
  38. windowLabel,
  39. payload
  40. }
  41. });
  42. }
  43. /**
  44. * Listen to an event from the backend.
  45. *
  46. * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
  47. * @param handler Event handler callback.
  48. * @return A promise resolving to a function to unlisten to the event.
  49. */
  50. async function listen(event, windowLabel, handler) {
  51. return invokeTauriCommand({
  52. __tauriModule: 'Event',
  53. message: {
  54. cmd: 'listen',
  55. event,
  56. windowLabel,
  57. handler: transformCallback(handler)
  58. }
  59. }).then((eventId) => {
  60. return async () => _unlisten(event, eventId);
  61. });
  62. }
  63. /**
  64. * Listen to an one-off event from the backend.
  65. *
  66. * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
  67. * @param handler Event handler callback.
  68. * @returns A promise resolving to a function to unlisten to the event.
  69. */
  70. async function once(event, windowLabel, handler) {
  71. return listen(event, windowLabel, (eventData) => {
  72. handler(eventData);
  73. _unlisten(event, eventData.id).catch(() => { });
  74. });
  75. }
  76. export { emit, listen, once };