- NativeScript 教程
- NativeScript - 首頁
- NativeScript - 簡介
- NativeScript - 安裝
- NativeScript - 架構
- NativeScript - Angular 應用
- NativeScript - 模板
- NativeScript - 小部件
- NativeScript - 佈局容器
- NativeScript - 導航
- NativeScript - 事件處理
- NativeScript - 資料繫結
- NativeScript - 模組
- NativeScript - 外掛
- NativeScript - 使用 JavaScript 的原生 API
- NativeScript - 在 Android 中建立應用程式
- NativeScript - 在 iOS 中建立應用程式
- NativeScript - 測試
- NativeScript 有用資源
- NativeScript - 快速指南
- NativeScript - 有用資源
- NativeScript - 討論
NativeScript - 事件處理
在每個GUI應用程式中,事件在啟用使用者互動方面都扮演著非常重要的角色。每當使用者與應用程式互動時,都會觸發一個事件,並執行相應的操作。
例如,當用戶單擊應用程式登入頁面上的登入按鈕時,它會觸發登入過程。
事件涉及兩個參與者:
事件傳送者 - 觸發實際事件的物件。
事件監聽器 - 監聽特定事件並在觸發事件時執行的函式。
Observable 類
這是一個用於處理事件的預定義類。其定義如下:
const Observable = require("tns-core-modules/data/observable").Observable;
在 NativeScript 中,幾乎每個物件都派生自 Observable 類,因此每個物件都支援事件。
事件監聽器
讓我們在本節中瞭解如何建立物件並向物件新增事件監聽器。
步驟 1
建立一個用於生成事件的按鈕,如下所示:
const Button = require("tns-core-modules/ui/button").Button;
const testButton = new Button();
步驟 2
接下來,按如下所示向按鈕新增文字:
testButton.text = "Click";
步驟 3
建立一個函式 onTap,如下所示:
let onTap = function(args) {
console.log("you clicked!");
};
步驟 4
現在將 tap 事件附加到 onTap 函式,如下所示:
testButton.on("tap", onTap, this);
另一種新增事件監聽器的方法如下:
testButton.addEventListener("tap", onTap, this);
步驟 5
透過 UI 本身附加事件的另一種方法如下所示:
<Button text="click" (tap)="onTap($event)"></Button>
這裡,
$event 的型別為 EventData。EventData 包含兩個屬性,如下所示:
物件 - 用於觸發事件的可觀察例項。在本例中,它是 Button 物件。
EventName - 事件名稱。在本例中,它是 tap 事件。
步驟 6
最後,事件監聽器可以在任何時候分離/刪除,如下所示:
testButton.off(Button.onTap);
您也可以使用另一種格式,如下所示:
testButton.removeEventListener(Button.onTap);
修改 BlankNgApp
讓我們修改 BlankNgApp 應用程式以更好地理解 NativeScript 中的事件。
步驟 1
開啟主頁元件的 UI,src/app/home/home.component.html 並新增以下程式碼:
<ActionBar> <Label text="Home"></Label> </ActionBar> <StackLayout> <Button text='Fire an event' class="-primary" color='gray' (tap)='onButtonTap($event)'></Button> </StackLayout>
這裡,
tap 是事件,Button 是事件觸發器。
onButtonTap 是事件監聽器。
步驟 2
開啟主頁元件的程式碼,‘src/app/home/home.component.ts’ 並更新以下程式碼:
import { Component, OnInit } from "@angular/core";
import { EventData } from "tns-core-modules/data/observable";
import { Button } from "tns-core-modules/ui/button"
@Component({
selector: "Home",
templateUrl: "./home.component.html"
})
export class HomeComponent implements OnInit {
constructor() {
// Use the component constructor to inject providers.
}
ngOnInit(): void {
// Init your component properties here.
}
onButtonTap(args: EventData): void {
console.log(args.eventName);
const button = <Button>args.object;
console.log(button.text);
}
}
這裡,
新增新的事件監聽器 onButtonTap。
列印事件名稱 tap 和按鈕文字,在控制檯中觸發一個事件。
步驟 3
執行應用程式並點選按鈕。它會在控制檯中列印以下行。
LOG from device <device name>: tap LOG from device <device name>: Fire an event