TypeScript 中的事件處理
本文將說明TypeScript中的事件處理。
您可以透過程式碼範例學習事件處理方法及自訂事件。
YouTube Video
TypeScript 中的事件處理
TypeScript 中的事件處理方式與 JavaScript 相同。但 TypeScript 強化了型別安全,可透過合適的事件型別安全地處理事件。事件處理的基本是為 DOM 元素新增事件監聽器,並根據使用者操作執行動作。
新增事件監聽器
可使用 addEventListener 方法為 DOM 元素新增事件監聽器。例如,要處理點擊事件,操作如下:。
1const button = document.getElementById('myButton');
2if (button) {
3 button.addEventListener('click', (event) => {
4 console.log('Button was clicked');
5 });
6}- 在這段程式碼中,
addEventListener用於為指定的 DOM 元素註冊點擊事件的處理器。
TypeScript 中的事件型別
在 TypeScript 中,事件監聽器接收到的 event 物件會自動分配合適的型別。event 物件的屬性會因事件型別不同而異,但其基礎型別為 Event。
根據每種事件使用適合的型別,就能在開發中充份發揮 TypeScript 的型別安全性。
主要事件型別
EventEvent是一般事件的基礎類型。用於表單送出、頁面載入完成等情境。
1const form = document.getElementById('myForm');
2if (form) {
3 form.addEventListener('submit', (event: Event) => {
4 event.preventDefault(); // Prevent the default form submission
5 console.log('Form was submitted');
6 });
7}- 這段程式碼會偵測表單的提交事件,阻止預設的提交動作,並在控制台輸出訊息。
-
MouseEventMouseEvent是與滑鼠操作相關的事件類型,如點擊或滑鼠移動。你可以取得滑鼠座標及被按下的按鈕資訊。
1const button = document.getElementById('myButton');
2if (button) {
3 button.addEventListener('click', (event: MouseEvent) => {
4 // Log the click position
5 console.log(`Click position: X=${event.clientX}, Y=${event.clientY}`);
6 });
7}- 這段程式碼會在按鈕被點擊時取得滑鼠座標並在控制台顯示。
KeyboardEventKeyboardEvent是與鍵盤輸入有關的事件類型。你可以存取被按下的鍵以及修飾鍵(Shift、Alt、Ctrl 等)的狀態。
1document.addEventListener('keydown', (event: KeyboardEvent) => {
2 // Log the pressed key
3 console.log(`Key pressed: ${event.key}`);
4 if (event.ctrlKey) {
5 // Log that the Ctrl key was pressed
6 console.log('Ctrl key was pressed');
7 }
8});- 這段程式碼會顯示按下的按鍵名稱,若有按住Ctrl鍵,也會在控制台輸出該訊息。
InputEventInputEvent是與輸入欄位變化有關的事件類型。用於文字輸入框或 textarea 的值變更時。
1const input = document.getElementById('myInput') as HTMLInputElement;
2if (input) {
3 input.addEventListener('input', (event: InputEvent) => {
4 // Log the entered value
5 console.log(`Entered value: ${input.value}`);
6 });
7}- 這段程式碼每當輸入欄位內容發生變化時,會在控制台顯示其內容。
FocusEventFocusEvent是元素取得或失去焦點時發生的事件類型。
1const input = document.getElementById('myInput');
2if (input) {
3 input.addEventListener('focus', (event: FocusEvent) => {
4 // Log when the input gains focus
5 console.log('Focused');
6 });
7
8 input.addEventListener('blur', (event: FocusEvent) => {
9 // Log when the input loses focus
10 console.log('Blurred');
11 });
12}- 這段程式碼會在輸入欄位獲得焦點時於控制台顯示「Focused」,失去焦點時顯示「Blurred」。
使用型別斷言處理自訂事件
對於自訂事件或 TypeScript 的型別推斷無法正常運作時,你可以用型別斷言明確指定型別。
例如要處理特定輸入欄位(HTMLInputElement)的事件時,可以如下指定型別:。
1const input = document.getElementById('myInput') as HTMLInputElement;
2if (input) {
3 input.addEventListener('input', (event: Event) => {
4 const target = event.target as HTMLInputElement;
5 // Log the entered value
6 console.log(`Entered value: ${target.value}`);
7 });
8}- 這段程式碼使用型別斷言將事件目標當作
HTMLInputElement,並在控制台顯示其值。
移除事件監聽器
你可以使用 removeEventListener 移除事件監聽器。為此,必須傳入與最初新增時相同的事件處理函式。
1const button = document.getElementById('myButton');
2
3const handleClick = (event: MouseEvent) => {
4 // Log when the button is clicked
5 console.log('Button was clicked');
6};
7
8if (button) {
9 button.addEventListener('click', handleClick);
10
11 // Remove the event listener later
12 button.removeEventListener('click', handleClick);
13}- 這段程式碼為按鈕新增點擊事件監聽器,之後再指定相同處理器來移除它。
建立自訂事件
在 TypeScript 中,除了標準事件外,也可以建立並派發自訂事件。可以用 CustomEvent 類別建立自訂事件,再用 dispatchEvent 觸發該事件。
1const customEvent = new CustomEvent('myCustomEvent', { detail: { name: 'TypeScript' } });
2const div = document.getElementById('myDiv');
3
4if (div) {
5 div.addEventListener('myCustomEvent', (event: CustomEvent) => {
6 // Log when the custom event is fired
7 console.log(`Custom event was triggered: ${event.detail.name}`);
8 });
9
10 div.dispatchEvent(customEvent); // Dispatch the custom event
11}- 這段程式碼利用
CustomEvent建立自訂事件,觸發該元素,並在控制台顯示事件詳情。
控制事件傳遞
事件發生時,預設會冒泡(傳遞到父元素)。若要防止冒泡傳遞,請使用 event.stopPropagation()。你也可以用 preventDefault() 阻止瀏覽器的預設行為。
1const button = document.getElementById('myButton');
2if (button) {
3 button.addEventListener('click', (event: MouseEvent) => {
4 event.preventDefault(); // Prevent the default action
5 event.stopPropagation(); // Stop the event propagation
6
7 // Log that event handling has been customized
8 console.log('Custom event handling');
9 });
10}- 這段程式碼在按下按鈕時阻止預設動作,停止事件冒泡,並執行自訂處理。
總結
在 TypeScript 中處理事件與 JavaScript 基本相同,但若有正確的型別定義,可更安全且可靠地操作事件物件與 DOM 元素。透過新增及移除事件監聽器、指定事件型別及使用型別斷言,可以讓事件處理邏輯更清楚也更少出錯。
您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。