ExampleJsInterop.cs
1,059 bytes
| 1 | using Microsoft.JSInterop; |
|---|---|
| 2 | |
| 3 | namespace SplitApp.Modules.Expenses.Api; |
| 4 | |
| 5 | // This class provides an example of how JavaScript functionality can be wrapped |
| 6 | // in a .NET class for easy consumption. The associated JavaScript module is |
| 7 | // loaded on demand when first needed. |
| 8 | // |
| 9 | // This class can be registered as scoped DI service and then injected into Blazor |
| 10 | // components for use. |
| 11 | |
| 12 | public class ExampleJsInterop(IJSRuntime jsRuntime) : IAsyncDisposable |
| 13 | { |
| 14 | private readonly Lazy<Task<IJSObjectReference>> moduleTask = new(() => jsRuntime.InvokeAsync<IJSObjectReference>( |
| 15 | "import", "./_content/SplitApp.Modules.Expenses.Api/exampleJsInterop.js").AsTask()); |
| 16 | |
| 17 | public async ValueTask<string> Prompt(string message) |
| 18 | { |
| 19 | var module = await moduleTask.Value; |
| 20 | return await module.InvokeAsync<string>("showPrompt", message); |
| 21 | } |
| 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 | |