A simple Blazor package to help you with event emitting and handling inside of WebViews written using Blazor. The package is meant for Blazor WASM only, however it should also work on Blazor Server, but you might encounter some unexpected behaviour.
Add nuget package
dotnet add package AltVBlazor --version 0.2.0
- Register AltVBlazor services to your DI container in
program.cs
builder.Services.AddAltVBlazor();
- Add AltVBlazor server Javascript file to wwwroot/index.html
<script src="_content/AltVBlazor/AltVBlazorEvents.js"></script>
You can either have your component inherit from AltVComponentBase
, or inject IAltVEventSubscriber
and subscribe to events yourself
To register an event handler, create a method and add JSInvokable
and AltVEvent
attributes
events will be automatically subscribed.
if you override OnInitializedAsync
make sure to call `base.OnInitializedAsync();' or events will not be subscribed.
@inherits AltVComponentBase
@code {
private bool chatInputVisible = false;
private readonly List<ChatMessage> messages = [];
[JSInvokable]
[AltVEvent("addChatMessage")]
public void OnChatMessageAdded(string json)
{
var chatMessage = ChatMessageExtensions.Deserialize(json);
messages.Add(chatMessage);
StateHasChanged();
}
[JSInvokable]
[AltVEvent("toggleChat")]
public void OnToggleChat(bool toggle)
{
chatInputVisible = toggle;
StateHasChanged();
}
}
Inject IAltVEventSubscriber
and call IAltVEventSubscriber.SubscribeEventsForComponent
when the component is initialized.
@inject IAltVEventSubscriber AltVEventSubscriber
@code {
private bool chatInputVisible = false;
private readonly List<ChatMessage> messages = [];
protected override async Task OnInitializedAsync()
{
await AltVEventSubscriber.SubscribeEventsForComponent(this);
await base.OnInitializedAsync();
}
[JSInvokable]
[AltVEvent("addChatMessage")]
public void OnChatMessageAdded(string json)
{
var chatMessage = ChatMessageExtensions.Deserialize(json);
messages.Add(chatMessage);
StateHasChanged();
}
[JSInvokable]
[AltVEvent("toggleChat")]
public void OnToggleChat(bool toggle)
{
chatInputVisible = toggle;
StateHasChanged();
}
}
if your component inherits from AltVComponentBase
, use Emit
method
private async void OnSubmit(object? sender, string e)
{
await Emit(ChatWebViewEvents.SubmitChatInput, e);
}
otherwise, inject IAltVEventEmitter
@inject IAltVEventEmitter Emitter
@code {
private async void OnSubmit(object? sender, string e)
{
await Emitter.Emit(ChatWebViewEvents.SubmitChatInput, e);
}
}
If you open Blazor APP in a browser, all emit events will be logged to the console. In addition to that, you can trigger callbacks using
window.dispatchEvent(new CustomEvent('eventName', {detail: argArray}));