Skip to content

Improve readability of Blazor Event Handling doc#21755

Merged
guardrex merged 6 commits into
mainfrom
guardrex/blazor-event-handling
Mar 18, 2021
Merged

Improve readability of Blazor Event Handling doc#21755
guardrex merged 6 commits into
mainfrom
guardrex/blazor-event-handling

Conversation

@guardrex
Copy link
Copy Markdown
Collaborator

@guardrex guardrex commented Mar 11, 2021

@guardrex
Copy link
Copy Markdown
Collaborator Author

guardrex commented Mar 15, 2021

@mkArtakMSFT ... This PR will need one more pass ⚒️ on Tuesday morning, but UPDATE: Pass complete. 👍 I think you can look at the section for custom event args and provide feedback. See if this link will spawn the section ...

Internal Review Topic (links to the Custom event arguments section)

If that link doesn't work because it won't open the 6.0 version of the topic, scroll the diff to Line 137.

@guardrex guardrex marked this pull request as ready for review March 16, 2021 14:14
@guardrex guardrex requested a review from mkArtakMSFT March 16, 2021 14:54
@guardrex guardrex closed this Mar 16, 2021
@guardrex guardrex reopened this Mar 16, 2021
@guardrex
Copy link
Copy Markdown
Collaborator Author

@mkArtakMSFT ... I'm going to go ahead with this initial coverage to clear this one through. It has a lot of other good UE updates on it. I'll paste the coverage in here for a quick scan. If you spot anything that you don't like, I'm 👂 and will react with a patch PR.

::: moniker range=">= aspnetcore-6.0"

Custom event arguments

Blazor supports custom event arguments, which enable you to pass arbitrary data to .NET event handlers with custom events.

General configuration

Custom events with custom event arguments are generally enabled with the following steps.

  1. In JavaScript, 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
      };
    }
  2. Register the custom event with the preceding handler in wwwroot/index.html (Blazor WebAssembly) or Pages/_Host.cshtml (Blazor Server) immediately after the Blazor <script>:

    <script>
        Blazor.registerCustomEventType('customevent', {
            createEventArgs: eventArgsCreator;
        });
    </script>

    [!NOTE]
    The call to registerCustomEventType is performed in a script only once per event.

  3. Define a class for the event arguments:

    public class CustomEventArgs : EventArgs
    {
        public string CustomProperty1 {get; set;}
        public string CustomProperty2 {get; set;}
    }
  4. Wire up the custom event with the event arguments by adding an xref:Microsoft.AspNetCore.Components.EventHandlerAttribute attribute annotation for the custom event. The class doesn't require members:

    [EventHandler("oncustomevent", typeof(CustomEventArgs), enableStopPropagation: true, enablePreventDefault: true)]
    static class EventHandlers
    {
    }
  5. Register the event handler on one or more HTML elements. Access the data that was passed in from Javascript in the delegate handler method:

    <button @oncustomevent="HandleCustomEvent">Handle</button>
    
    @code
    {
        void HandleCustomEvent(CustomEventArgs eventArgs)
        {
            // eventArgs.CustomProperty1
            // eventArgs.CustomProperty2
        }
    }

Whenever the custom event is fired on the DOM, the event handler is called with the data passed from the Javascript.

If you're attempting to fire a custom event, bubbles must be enabled by setting its value to true. Otherwise, the event doesn't reach the Blazor handler for processing into the C# custom xref:Microsoft.AspNetCore.Components.EventHandlerAttribute method. For more information, see MDN Web Docs: Event bubbling.

Custom clipboard paste event example

The following example receives a custom clipboard paste event that includes the time of the paste and the user's pasted text.

Declare a custom name (oncustompaste) for the event and a .NET class (CustomPasteEventArgs) to hold the event arguments for this event:

CustomEvents.cs:

[EventHandler("oncustompaste", typeof(CustomPasteEventArgs), 
    enableStopPropagation: true, enablePreventDefault: true)]
public static class EventHandlers
{
}

public class CustomPasteEventArgs : EventArgs
{
    public DateTime EventTimestamp { get; set; }
    public string PastedData { get; set; }
}

Add JavaScript code to supply data for the xref:System.EventArgs subclass. In the wwwroot/index.html or Pages/_Host.cshtml file, add the following <script> tag and content immediately after the Blazor script. The following example only handles pasting text, but you could use arbitrary JavaScript APIs to deal with users pasting other types of data, such as images.

wwwroot/index.html (Blazor WebAssembly) or Pages/_Host.cshtml (Blazor Server) immediately after the Blazor script:

<script>
    Blazor.registerCustomEventType('custompaste', {
        browserEventName: 'paste',
        createEventArgs: event => {
            return {
                eventTimestamp: new Date(),
                pastedData: event.clipboardData.getData('text')
            };
        }
    });
</script>

The preceding code tells the browser that when a native paste event occurs:

  • Raise a custompaste event.
  • Supply the event arguments data using the custom logic stated:

Event name conventions differ between .NET and JavaScript:

  • In .NET, event names are prefixed with "on".
  • In JavaScript, event names don't have a prefix.

In a Razor component, attach the custom handler to an element.

Pages/CustomPasteArguments.razor:

@page "/custom-paste-arguments"

<label>
    Try pasting into the following text box:
    <input @oncustompaste="HandleCustomPaste" />
</label>

<p>
    @message
</p>

@code {
    private string message;

    private void HandleCustomPaste(CustomPasteEventArgs eventArgs)
    {
        message = $"At {eventArgs.EventTimestamp.ToShortTimeString()}, " +
            $"you pasted: {eventArgs.PastedData}";
    }
}

::: moniker-end

@guardrex guardrex merged commit ad8dc8f into main Mar 18, 2021
@guardrex guardrex deleted the guardrex/blazor-event-handling branch March 18, 2021 02:06
@scottaddie scottaddie changed the title Blazor Event Handling UE Pass Improve readability of Blazor Event Handling doc Apr 1, 2021
@guardrex guardrex mentioned this pull request Apr 13, 2021
41 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add documentation for Blazor custom event args feature

1 participant