Reputation: 512
Might be a silly question. But is there a way to re-use methods that call Javascript functions in runtime?
So let's say I have EditBox.razor
component that has this function
@inject IJSRuntime JSRuntime
...
Some HTML code
...
@code{
...
private async Task RenderSyntax()
{
await JSRuntime.InvokeVoidAsync("Prism.highlightAll");
}
...
Now I want to call this method in some other component Foo.razor
. Without having reference, so statically.
Do I create a static class model for generic Javascript.razor
components where I define all my javascript interops that are called by different components and make all other components inherit it?
Upvotes: 1
Views: 1683
Reputation: 3216
You can create a helper class for e.g. JSInteropHelper. This will have your reusable methods that you want to use in multiple pages.
// Have kept the method as static so I don't need to create a instance of it.
internal static ValueTask<object> HighlightText(IJSRuntime jsRuntime)
{
return jsRuntime.InvokeAsync<object>("Prism.highlightAll");
}
In your razor component you can just pass the JSRuntime
as parameter.
@code{
private async Task RenderSyntax()
{
await JSInteropHelper.HighlightText(JSRuntime);
}
}
Upvotes: 2
Reputation: 5481
As HannesPreishuber mentioned, you can create a class and add all your methods in it and use that class everywhere via dependency injection. Here is an example code:
public class JsMethods : IJsMethods
{
private readonly IJSRuntime _jSRuntime;
public JsMethods(IJSRuntime jsRuntime)
{
_jSRuntime = jSRuntime;
}
public async Task RenderSyntax(string identifier)
{
//.. some other code
await JSRuntime.InvokeVoidAsync(identifier);
//.. some other code
}
}
Upvotes: 0
Reputation: 342
this is the idea of Dependency Injection (DI) a static class is a kind of DI singleton object. So dont do it an take the way Microsoft decided. You can encapsulate this logic into a wrapper class (mylib) and attach it to the di list in startup.cs like AddSingleton https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1
Upvotes: 0