When developing a website, we may want to respond to certain events with specific event data models that are different from the event data we receive from a standard event, such as a click event. Fortunately, Blazor WebAssembly provides a way to register our events and return our custom event arguments.
Let’s start.
How To Make Custom Event Arguments In Blazor
Being able to define custom event arguments allows us to easily define complex behavior and write shorter code that is more readable.
We can break down the process of defining and utilizing custom event arguments into three steps.
First, we must define a model class for the custom event argument and define the relationship between the custom argument and an event attribute name using the [EventHandler()]
decorator.
Second, we write a script to return our custom event arguments when a standard event occurs.
Lastly, our event handler catches the custom event arguments specifically created to react to our event defined in the first step.
There are many standard browser events we can use to write custom event arguments for our own purposes. For example, we can make custom events for the clipboard, mouse, focus, keyboard, and drag to name just a few. We can refer to this article on official Microsoft Blazor documentation for a comprehensive list of event types.
This article will define a custom event and event arguments for a double click on a button.
Create Blazor Event Argument Classes And Data Model
Let’s begin by defining a custom event argument model class:
public class DoubleClickEventArgs : EventArgs { public DateTime? EventTimestamp { get; set; } public bool IsDoubleClick { get; set; } }
Next, let’s define a static class that must be named EventHandlers
. We can decorate this class with the EventHandler
attribute:
[EventHandler("ondoubleclick", typeof(DoubleClickEventArgs), enableStopPropagation: true, enablePreventDefault: true)] public static class EventHandlers { // purposefully empty }
Here we define an event ondoubleclick
whose argument is of type DoubleClickEventArgs
. Doing this will allow us to set custom method handlers for ondoubleclick
event.
In the next section, we will write a script to detect a double click and return an instance of our custom DoubleClickEventArgs
.
Bind Custom Event To A Browser Event
Now, we will need to tell the browser that we want to register a custom event based on the standard click
browser event. We can do this by adding a <script/>
to the wwwroot/index.html
file.
Let’s look at how we can determine if the user has double-clicked a component:
//index.html <script> let lastClick = 0; const MAX_DOUBLE_CLICK_TIME = 400 Blazor.registerCustomEventType('doubleclick', { browserEventName: 'click', createEventArgs: event => { const timeBetweenClicks = event.timeStamp - lastClick if (timeBetweenClicks > MAX_DOUBLE_CLICK_TIME) { lastClick = event.timeStamp; return { eventTimestamp: new Date(), isDoubleClick: false }; } // Double click happened. console.log("double click!"); lastClick = 0 return { eventTimestamp: new Date(), isDoubleClick: true }; } }); </script>
In this script, we define a double click as two clicks in less than 400ms. This script will return a DoubleClickEventArgs
with the isDoubleClick
property set. Our script will be run each time a click
event is raised by the web browser. Note that this script should be placed after the blazor.webassembly.js
script.
Next, we will use our custom event with a button component and write our double-click handler function.
Use A Custom Event in Blazor
First, let’s add a button, a message to display if we detect a double click, and a double click handler method:
<button @ondoubleclick="HandleDoubleClick"> Click Me </button> <h1>@message</h1> @code { string message; void HandleDoubleClick(DoubleClickEventArgs eventArgs) { if (eventArgs is not null && eventArgs.isDoubleClick) { message = "Detected double click!"; } else { message = ""; } } }
Taking a look at our button component, we set HandleDoubleClick()
as our event handler for @ondoubleclick
. The heading element (<h1>
) will display the value of message
.
In HandleDoubleClick()
we receive the DoubleClickEventArgs
event data from our script in the previous section. If a double click was detected we will update the value of message
. Setting message
will display it and alert us that the user double-clicked. If there was no double click we will set message
to empty. Consequently, this will make the message disappear in case the last button interaction was not a double click.
Conclusion
In conclusion, we can follow these steps to implement custom browser events in Blazor. Custom events allow us to react to specific user inputs and actions while clearly defining behavior. There are a significant number of browser events for which we can write custom event handling. We can surely use them to write better web applications.