이벤트 처리

2022. 5. 5. 00:00ASPNET/Blazor

반응형

Razor 구성 요소 태그에서 이벤트 처리기 지정 방법

 @on{DOM EVENT}="{DELEGATE}"

 

{DOM EVENT} :  DOM(문서 개체 모델) 이벤트 (예: click)
{DELEGATE} : C# 대리자 이벤트 처리기

 

  • Task를 반환하는 비동기 대리자 이벤트 처리기가 지원된다.
  • 대리자 이벤트 처리기는 UI 렌더링을 자동으로 트리거하므로 
    StateHasChanged를 수동으로 호출할 필요가 없다.
  • 예외가 기록됩니다.

Pages/EventHandlerExample1.razor

@page "/event-handler-example-1"

<h1>@currentHeading</h1>

<p>
    <label>
        New title
        <input @bind="newHeading" />
    </label>
    <button @onclick="UpdateHeading">
        Update heading
    </button>
</p>

<p>
    <label>
        <input type="checkbox" @onchange="CheckChanged" />
        @checkedMessage
    </label>
</p>

@code {
    private string currentHeading = "Initial heading";
    private string? newHeading;
    private string checkedMessage = "Not changed yet";

    private void UpdateHeading()
    {
        currentHeading = $"{newHeading}!!!";
    }

    private void CheckChanged()
    {
        checkedMessage = $"Last changed at {DateTime.Now}";
    }
}

Pages/EventHandlerExample2.razor

@page "/event-handler-example-2"

<h1>@currentHeading</h1>

<p>
    <label>
        New title
        <input @bind="newHeading" />
    </label>
    <button @onclick="UpdateHeading">
        Update heading
    </button>
</p>

@code {
    private string currentHeading = "Initial heading";
    private string? newHeading;

    private async Task UpdateHeading()
    {
        await Task.Delay(2000);

        currentHeading = $"{newHeading}!!!";
    }
}

 

Event arguments

 

MouseEventArgs 를 이용하여 mouse 의 포지션을 알아오는 예제

Pages/EventHandlerExample3.razor

@page "/event-handler-example-3"
<div @onclick="ReportPointerLocation"  style="height:500px;background-color: ivory">
    ㅋㅋㅋ
</div>

<p>@mousePointerMessage</p>

@code {
    private string? mousePointerMessage;

    private void ReportPointerLocation(MouseEventArgs e)
    {
        mousePointerMessage = $"Mouse coordinates: {e.ScreenX}:{e.ScreenY}";
    }
}

 

사용자 지정 클립보드 붙여넣기 이벤트 예제

Data/CustomEvents.cs

using Microsoft.AspNetCore.Components;

namespace BlazorTutorial.Data;
[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; }
    public bool IsMultimedia { get; set; }
}

Pages/_Layout.cshtml

 

참조 https://gavilan.blog/2021/05/08/blazor-net-6-custom-events-pasting-images-like-on-twitter-asp-net-core-6/

<body>
....
    <script>
        Blazor.registerCustomEventType("custompaste", {
            browserEventName: 'paste',
            createEventArgs: event => {
                let isMultimedia = false;

                // We get the saved text in the clipboard
                let pastedData = event.clipboardData.getData('text');

                const items = event.clipboardData.items;

                // With this we'll filter the file by its media type
                const acceptedMediaTypes = ['image/png'];

                for (let i = 0; i < items.length; i++) {
                    const file = items[i].getAsFile();

                    // We verify there's a file in the current item
                    if (!file) {
                        continue;
                    }

                    // We verify the media type of the file
                    if (acceptedMediaTypes.indexOf(items[i].type) === -1) {
                        continue;
                    }

                    // it's an image
                    isMultimedia = true;
                    const url = window.URL || window.webkitURL;
                    pastedData = url.createObjectURL(file);
                }

                // We are passing the information to the custom event from JavaScript
                return {
                    eventTimestamp: new Date(),
                    isMultimedia,
                    pastedData
                }
            }
        })
    </script>
...
</body>

Pages/CustomPasteArguments.razor

@page "/custom-paste-arguments"
@using BlazorTutorial.Data
<div @oncustompaste="HandleCustomPaste" style="height:500px;background-color: ivory">>
    <label>
        Try pasting into the following text box:
    </label>
    @foreach (var image in images)
    {
        <img style="width: 150px; margin-right: 1rem; margin-top: 1rem" src="@image" />
    }
</div>

<p>
    @message
</p>

@code {
    private string? message;
    private List<string> images = new List<string>();

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

        if (eventArgs.IsMultimedia)
        {
            images.Add(eventArgs.PastedData??string.Empty);
        }
    }
}

 

 

관련영상

https://youtu.be/kxcGNxDTGpI

 

반응형

'ASPNET > Blazor' 카테고리의 다른 글

Blazor web app 이란 무엇인가? (dotnet 8)  (0) 2023.12.04
이벤트 처리 2  (0) 2022.05.06
Binding 3  (0) 2022.05.04
Binding 2  (0) 2022.05.03
Binding 1  (0) 2022.05.02