Skip to content

Add documentation for Blazor custom event args feature #21763

@mkArtakMSFT

Description

@mkArtakMSFT

This is a request to add documentation for Blazor Custom Event arguments feature which is (going to be) introduced as part of 6.0-preview2 release.
The feature enables the following two scenarios:

  1. Capture additional event data from the DOM in .NET
  2. Register custom event handlers in DOM and handle those in .NET

Draft writeup for the first scenario can be found from the 6.0-preview2 announcement blog post.
For the second scenario, please use the draft from below:

///////////////////////////////////////////////////////////////
Blazor's support for custom events is now expanded to also support custom event arguments.
This allows passing arbitrary data to .NET event handlers with custom events.

Follow the steps below to define a custom event with custom event argument(s):

** on the JavaScript side

  • define a function for building the custom event argument object from the source event
function eventArgsCreator(event) { 
 return {
   customProperty1: 'any value for property 1',
   customProperty2: event.srcElement.value
 };
}
  • register the custom event with the above created handler
Blazor.registerCustomEventType('customevent', {
    createEventArgs: eventArgsCreator;

Note, that the above call is done in a javascript and can be called only once (per each event).

** on the .NET side
3. define a class for the event args

public class CustomEventArgs : EventArgs{
    public string CustomProperty1 {get; set;}
    public string CustomProperty2 {get; set;}
}
  1. wire up the custom event with the event args by adding an EventHandler attribute annotation for your custom event:
[EventHandler("oncustomevent", typeof(CustomEventArgs), enableStopPropagation: true, enablePreventDefault: true)]
static class EventHandlers
{
}
  1. Register your event handler on the HTML element you expect to handle the event for:
<button @oncustomevent="HandleCustomEvent">Handle</button>

@code
{
    void HandleCustomEvent(CustomEventArgs eventArgs)
    {
        // here you can access the data which was passed in from the Javascript side
    }
}

Now, whenever the custom event is fired on the DOM, your event handler will be called with the data passed from the Javascript.
Note, that if you're trying to fire a custom event, you'll need to make sure that it has to have bubbles: true, as otherwise it won't get to the Blazor handler to process it.

Metadata

Metadata

Assignees

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions