امکان تبدیل رخدادهای توکار مرورگرها به دایرکتیوهای Blazor در Blazor6x
یکسری دایرکتیو مانند onclick@ و امثال آن، از پیش در Blazor تعریف شدهاند که امکان مدیریت رویدادهای جاوااسکریپتی را در کدهای سیشارپ میسر میکنند. اما تعداد اینها زیاد نیست. برای مثال تعداد رویدادهای قابل تعریف و پشتیبانی شدهی توسط مرورگرها
قابل ملاحظهاست. در Blazor 6x روشی جهت دسترسی سادهتر به این رویدادها ارائه شدهاست که شامل این مراحل است. برای نمونه فرض کنید میخواهیم به رویداد
paste مرورگر دسترسی پیدا کنیم و یک دایرکتیو سفارشی oncustompaste@ را برای آن تهیه کنیم:
<input @oncustompaste="HandleCustomPaste" />
برای اینکار در ابتدا قطعه کد زیر را پس از blazor.webassembly.js
در فایل index.html ثبت میکنیم (یا میتوان از روش export function afterStarted که در بالا عنوان شد هم استفاده کرد):
<script>
Blazor.registerCustomEventType('custompaste', {
browserEventName: 'paste',
createEventArgs: event => {
// This example only deals with pasting text, but you could use arbitrary JavaScript APIs
// to deal with users pasting other types of data, such as images
return {
eventTimestamp: new Date(),
pastedData: event.clipboardData.getData('text')
};
}
});
</script>
در اینجا برای رویداد paste مرورگر، تعدادی آرگومان تهیه شده و بازگشت داده میشود. آرگومان اول در اینجا یک مقدار اختیاری و نمایشیاست و آرگومان دوم به شیء رویداد paste، دسترسی یافته و
متن آنرا بازگشت میدهد.
پس از اینکار، معادل دو پارامتر بازگشت داده شده را به صورت زیر در کدهای سیشارپ تهیه میکنیم:
namespace BlazorCustomEventArgs.CustomEvents
{
[EventHandler("oncustompaste", typeof(CustomPasteEventArgs), enableStopPropagation: true, enablePreventDefault: true)]
public static class EventHandlers
{
// This static class doesn't need to contain any members. It's just a place where we can put
// [EventHandler] attributes to configure event types on the Razor compiler. This affects the
// compiler output as well as code completions in the editor.
}
public class CustomPasteEventArgs : EventArgs
{
// Data for these properties will be supplied by custom JavaScript logic
public DateTime EventTimestamp { get; set; }
public string PastedData { get; set; }
}
}
ابتدا از EventArgs
ارثبری شده و معادل تاریخ و متن بازگشت داده شده، تبدیل به یک EventArgs سفارشی میشود. سپس نوع آن، به ویژگی EventHandler ای که بالای یک کلاس استاتیک خالی قرار گرفته شده، ارسال میشود. اینکار صرفا جهت اطلاع کامپایلر صورت میگیرد. یک نکته: در اینجا نام
oncustompaste
به همان نام custompaste کدهای جاوااسکریپتی اشاره میکند. نام تعریف شدهی در قسمت سیشارپ، یک on در ابتدا اضافهتر دارد. اینکار سبب میشود که اکنون بتوان یک رویدادگردان oncustompaste@ سفارشی را که قابل مدیریت در کدهای سیشارپ است، داشت:
@page "/"
<p>Try pasting into the following text box:</p>
<input @oncustompaste="HandleCustomPaste" />
<p>@message</p>
@code {
string message;
void HandleCustomPaste(CustomPasteEventArgs eventArgs)
{
message = $"At {eventArgs.EventTimestamp.ToShortTimeString()}, you pasted: {eventArgs.PastedData}";
}
}