We are attempting to build a Blazor wrapper for our native Javascript web component library.
Our input emits a custom event valueChange whenever the user changes the value of the text field (i.e.: types/deletes stuff in it). We want to capture this event and retrieve the detail property in the CustomEvent, which contains the current text box's text:
library-input.js:
#updateValue(value) { // ... updating the native `value` attribute const valueEvent = new CustomEvent("valueChange", { detail: this.#value, bubbles: true, }); this.dispatchEvent(valueEvent);}libraryInput.razor:
@inject IJSRuntime JSRuntime@namespace BlazorWrapperForLibrary@using System.Text.Json<lib-input @ref="libInput" @onvalueChange="ValueChanged"></lib-input>@code { private ElementReference libInput; private const string JAVASCRIPT_FILE = "/js/library-components.js"; private const string INTEROP_FILE = "/js/lib-input.interop.js"; private IJSObjectReference? Module { get; set; } private IJSObjectReference? Interop { get; set; } [Parameter] public string? Value { get; set; } [Parameter] public EventCallback<InputValueChangeEventArgs> ValueChanged {get; set;} protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { Module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", JAVASCRIPT_FILE); Interop = await JSRuntime.InvokeAsync<IJSObjectReference>("import", INTEROP_FILE); } }}CustomEvents.cs:
public class InputValueChangeEventArgs : EventArgs{ public string? detail { get; set; }}[EventHandler("onvalueChange", typeof(InputValueChangeEventArgs), enableStopPropagation: true, enablePreventDefault: true)]public static class EventHandlers{}Counter.razor:
@page "/counter"<LibInput Value="newValue" ValueChanged="@((InputValueChangeEventArgs value) => InputChanged(value))"></LibInput>@code { private string newValue = "undefined"; private void InputChanged(InputValueChangeEventArgs value) { Console.WriteLine(value.detail); }}- When I add an event listener for the
valueChangeon thedocumentI can see thedetailproperty is filled successfully. - When I put a breakpoint in the JS for Blazor in the devtools (
onGlobalEvent(e)in theblazor.server.js) I can also see thedetailproperty filled in. - When I inspect the Web Socket Messages I see
......BeginInvokeDotNetFromJS..1..DispatchEventAsync..I[{"eventHandlerId":7,"eventName":"valueChange","eventFieldInfo":null},{}]. I'm not sure ifeventFieldInfo: nullhas anything to do with this. - When I put a breakpoint in the
InputChanged()method in theCounter.razorfile, thedetailproperty isnull.
