跳到主要内容

使用插件 API

在实现屏幕方向功能之前,先构建一个调用插件 API 的用户界面是合理的做法。本质上,我们想搭一个测试台,以便快速验证各平台的功能一致性。

本次演示的重点是如何构建 Napacitor 插件,而不是如何构建某个特定的前端框架应用,因此我们会刻意把界面做小——一个任何框架(甚至不用框架)都能驱动的 TypeScript 模块。

在应用的入口文件(例如 src/main.ts)中加入以下内容:

import { ScreenOrientation } from './plugins/screen-orientation';

// 跟踪当前方向,并在变化时更新界面。
let orientation = '';

ScreenOrientation.addListener('screenOrientationChange', res => {
orientation = res.type;
render();
});

ScreenOrientation.orientation().then(res => {
orientation = res.type;
render();
});

function render() {
// 按方向切换 DOM;装饰性细节从略。
document.body.className = orientation;
}

现在启动 Web 应用并打开浏览器的开发者工具:

npm run dev

你应该会看到如下错误:

Uncaught (in promise) ScreenOrientation does not have web implementation.

这个错误是正常的;我们还没有为任何平台编写实现。保持浏览器打开。我们会先实现 Web 平台,然后实现运行在 MAUI 宿主内的 C# 侧。

插件是如何被使用的?​

跟踪屏幕方向:

orientation 变量保存屏幕方向的值。它可以通过调用 render() 更新。由于代码开始执行时我们并不知道当前屏幕方向,它默认是空字符串。

监听变化:

我们建立了一个事件监听器,在 screenOrientationChange 触发时更新 orientation:

ScreenOrientation.addListener('screenOrientationChange', res => {
orientation = res.type;
render();
});

addListener 返回的监听器句柄有一个 remove() 方法;在界面销毁时调用它以停止接收事件。removeAllListeners() 会清除为该插件注册的所有监听器:

ScreenOrientation.removeAllListeners();

读取当前方向:

界面加载时获取当前屏幕方向:

ScreenOrientation.orientation().then(res => {
orientation = res.type;
render();
});

运行 npm run build,这样之后在 MAUI 宿主中运行应用时会使用新的界面。

现在我们有了一个调用插件 API 的用户界面,可以开始实现功能了!下一步我们先针对 Web 平台:Web 实现。