0

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?

3 Answers 3

1

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);
    }
}
1
  • 1
    Thank you for the answer. That is literally what I did yesterday, I just forgot to update this question. Thank you for the answer again. Commented Jul 9, 2020 at 19:05
0

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

0

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
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.