event.cjs 2.3 KB

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