From b269dd5e1ec3cbe79dcd60ba2677c7f5ef2439b1 Mon Sep 17 00:00:00 2001 From: AlexNek Date: Wed, 13 Nov 2024 13:16:12 +0100 Subject: [PATCH] ExampleJsInterop --- Babylon.Blazor.AppShared/ExampleJsInterop.cs | 37 +++++++++++++++++++ .../wwwroot/exampleJsInterop.js | 6 +++ 2 files changed, 43 insertions(+) create mode 100644 Babylon.Blazor.AppShared/ExampleJsInterop.cs create mode 100644 Babylon.Blazor.AppShared/wwwroot/exampleJsInterop.js diff --git a/Babylon.Blazor.AppShared/ExampleJsInterop.cs b/Babylon.Blazor.AppShared/ExampleJsInterop.cs new file mode 100644 index 0000000..af7568c --- /dev/null +++ b/Babylon.Blazor.AppShared/ExampleJsInterop.cs @@ -0,0 +1,37 @@ +using Microsoft.JSInterop; + +namespace BabylonBlazor.AppShared +{ + // This class provides an example of how JavaScript functionality can be wrapped + // in a .NET class for easy consumption. The associated JavaScript module is + // loaded on demand when first needed. + // + // This class can be registered as scoped DI service and then injected into Blazor + // components for use. + + public class ExampleJsInterop : IAsyncDisposable + { + private readonly Lazy> moduleTask; + + public ExampleJsInterop(IJSRuntime jsRuntime) + { + moduleTask = new(() => jsRuntime.InvokeAsync( + "import", "./_content/Babylon.Blazor.AppShared/exampleJsInterop.js").AsTask()); + } + + public async ValueTask Prompt(string message) + { + var module = await moduleTask.Value; + return await module.InvokeAsync("showPrompt", message); + } + + public async ValueTask DisposeAsync() + { + if (moduleTask.IsValueCreated) + { + var module = await moduleTask.Value; + await module.DisposeAsync(); + } + } + } +} diff --git a/Babylon.Blazor.AppShared/wwwroot/exampleJsInterop.js b/Babylon.Blazor.AppShared/wwwroot/exampleJsInterop.js new file mode 100644 index 0000000..ea8d76a --- /dev/null +++ b/Babylon.Blazor.AppShared/wwwroot/exampleJsInterop.js @@ -0,0 +1,6 @@ +// This is a JavaScript module that is loaded on demand. It can export any number of +// functions, and may import other JavaScript modules if required. + +export function showPrompt(message) { + return prompt(message, 'Type anything here'); +}