ExampleJsInterop.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. using Microsoft.JSInterop;
  2. namespace Avalonia.Web.Blazor
  3. {
  4. // This class provides an example of how JavaScript functionality can be wrapped
  5. // in a .NET class for easy consumption. The associated JavaScript module is
  6. // loaded on demand when first needed.
  7. //
  8. // This class can be registered as scoped DI service and then injected into Blazor
  9. // components for use.
  10. public class ExampleJsInterop : IAsyncDisposable
  11. {
  12. private readonly Lazy<Task<IJSObjectReference>> moduleTask;
  13. public ExampleJsInterop(IJSRuntime jsRuntime)
  14. {
  15. moduleTask = new(() => jsRuntime.InvokeAsync<IJSObjectReference>(
  16. "import", "./_content//exampleJsInterop.js").AsTask());
  17. }
  18. public async ValueTask<string> Prompt(string message)
  19. {
  20. var module = await moduleTask.Value;
  21. return await module.InvokeAsync<string>("showPrompt", message);
  22. }
  23. public async ValueTask DisposeAsync()
  24. {
  25. if (moduleTask.IsValueCreated)
  26. {
  27. var module = await moduleTask.Value;
  28. await module.DisposeAsync();
  29. }
  30. }
  31. }
  32. }