Update RCL template to use 5.0 features (#25613)
* Update JS interop to use auto-loaded ES6 module * Test update * Make it lazy for compatibility with prerendering * Update comment * Code style: go back to .AsTask - it's probably easier to read
This commit is contained in:
parent
d5a477ce1e
commit
9f5276d17a
|
|
@ -1,16 +1,39 @@
|
|||
using Microsoft.JSInterop;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.JSInterop;
|
||||
|
||||
namespace Company.RazorClassLibrary1
|
||||
{
|
||||
public class ExampleJsInterop
|
||||
// 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
|
||||
{
|
||||
public static ValueTask<string> Prompt(IJSRuntime jsRuntime, string message)
|
||||
private readonly Lazy<Task<IJSObjectReference>> moduleTask;
|
||||
|
||||
public ExampleJsInterop(IJSRuntime jsRuntime)
|
||||
{
|
||||
// Implemented in exampleJsInterop.js
|
||||
return jsRuntime.InvokeAsync<string>(
|
||||
"exampleJsFunctions.showPrompt",
|
||||
message);
|
||||
moduleTask = new (() => jsRuntime.InvokeAsync<IJSObjectReference>(
|
||||
"import", "./_content/Company.RazorClassLibrary1/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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,6 @@
|
|||
// This file is to show how a library package may provide JavaScript interop features
|
||||
// wrapped in a .NET API
|
||||
// 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.
|
||||
|
||||
window.exampleJsFunctions = {
|
||||
showPrompt: function (message) {
|
||||
return prompt(message, 'Type anything here');
|
||||
}
|
||||
};
|
||||
export function showPrompt(message) {
|
||||
return prompt(message, 'Type anything here');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -877,9 +877,9 @@
|
|||
"Files": [
|
||||
"wwwroot/background.png",
|
||||
"wwwroot/exampleJsInterop.js",
|
||||
"wwwroot/styles.css",
|
||||
"_Imports.razor",
|
||||
"Component1.razor",
|
||||
"Component1.razor.css",
|
||||
"ExampleJsInterop.cs"
|
||||
]
|
||||
},
|
||||
|
|
|
|||
Loading…
Reference in New Issue