KeiStory

728x90
반응형

C# Blazor 더블 클릭 방지하기

 

Button 클릭시 로직을 처리하는 경우 버튼의 더블 클릭을 방지하기위해 로딩창을 띄웁니다.

하지만 사용자가 빠르게 Double Click 를 하는 경우 로딩창이 뜨기전에 이벤트가 발생하게되어

이벤트 로직이 두번 수행되는 경우가 있습니다.

이를 방지하는 방법을 알아봅니다.

 

 

@page "/counter"

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<button class="btn btn-primary" disabled="@isBusy" @onclick="IncrementCountIsBusy">Click IsBusy (@currentCount)</button>

@code {

    private bool isBusy = false;

    [Parameter]
    public int Increment { get; set; } = 1;

    private int currentCount = 0;

    public async Task IncrementCountIsBusy()
    {
        if(isBusy)
        {
            return;
        }

        isBusy = true;

        try
        {
            await Task.Delay(2000);
            currentCount += Increment;
        }
        finally
        {
            isBusy = false;
        }
    }
}

위 코드를 보면 알수 있듯이 isBusy 인자를 이용해서 해당 인자값을 수행하는 동안 바꿔줌으로써 로직이 두번 수행되는 것을 방지합니다.

 

결과

아래 그림처럼 버튼 클릭시 버튼이 비활성화 되면서 추가 클릭이벤트를 방지하게됩니다.

 

참고
https://github.com/dotnet/aspnetcore/issues/23416

 

Blazor Server Issues when Double Clicking · Issue #23416 · dotnet/aspnetcore

We recently published a production blazor website which is currently visited by about 10000 people daily. We are seeing numerous reports from users describing all kinds of problems which we could n...

github.com

 

728x90

공유하기

facebook twitter kakaoTalk kakaostory naver band