Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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)
{
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()
{
// Implemented in exampleJsInterop.js
return jsRuntime.InvokeAsync<string>(
"exampleJsFunctions.showPrompt",
message);
if (moduleTask.IsValueCreated)
{
var module = await moduleTask.Value;
await module.DisposeAsync();
}
}
}
}
Original file line number Diff line number Diff line change
@@ -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');
}
2 changes: 1 addition & 1 deletion src/ProjectTemplates/test/template-baselines.json
Original file line number Diff line number Diff line change
Expand Up @@ -877,9 +877,9 @@
"Files": [
"wwwroot/background.png",
"wwwroot/exampleJsInterop.js",
"wwwroot/styles.css",
"_Imports.razor",
"Component1.razor",
"Component1.razor.css",
"ExampleJsInterop.cs"
]
},
Expand Down