Skip to content

Commit

Permalink
ExampleJsInterop
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexNek committed Nov 13, 2024
1 parent 7ba5b7e commit b269dd5
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
37 changes: 37 additions & 0 deletions Babylon.Blazor.AppShared/ExampleJsInterop.cs
Original file line number Diff line number Diff line change
@@ -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<Task<IJSObjectReference>> moduleTask;

public ExampleJsInterop(IJSRuntime jsRuntime)
{
moduleTask = new(() => jsRuntime.InvokeAsync<IJSObjectReference>(
"import", "./_content/Babylon.Blazor.AppShared/exampleJsInterop.js").AsTask());
}

public async ValueTask<string> Prompt(string message)
{
var module = await moduleTask.Value;
return await module.InvokeAsync<string>("showPrompt", message);
}

public async ValueTask DisposeAsync()
{
if (moduleTask.IsValueCreated)
{
var module = await moduleTask.Value;
await module.DisposeAsync();
}
}
}
}
6 changes: 6 additions & 0 deletions Babylon.Blazor.AppShared/wwwroot/exampleJsInterop.js
Original file line number Diff line number Diff line change
@@ -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');
}

0 comments on commit b269dd5

Please sign in to comment.