HarmonyOS API 9提供了EventHub组件,它提供了跟Android的EventBus一样的功能:EventHub模块提供了事件中心,提供订阅、取消订阅、触发事件的能力。下面使用Codelabs上一个简单的demo来讲解其具体用法:
Demo使用的版本:ArkTS-3.2.12.5
Demo实现效果:LoginPage->SuccessPage->HomePage
从登录页面跳转到登录成功页面然后跳转到首页。
首先在LoginPage
里注册一个EventHub
事件,主要是在aboutToApper方法里面注册:执行逻辑很简单就是一个简单的路由@ohos.router跳转。事件名是CommonConstants.HOME_PAGE_ACTION
import router from '@ohos.router';
@Entry
@Component
struct LoginPage {
@State account: string = '';
@State password: string = '';
@State isShadow: boolean = false;
private windowModel: WindowModel = WindowModel.getInstance();
aboutToAppear() {
//注册事件,执行路由跳转到首页
getContext(this).eventHub.on(CommonConstants.HOME_PAGE_ACTION, () => {
router.replaceUrl({
url: CommonConstants.HOME_PAGE_URL
}).catch((err: Error) => {
Logger.error(`pushUrl failed, message:${err.message}`);
});
});
}
}
在登录成功页面发起一个定时任务,2秒后通过eventHub的emit方法发起CommonConstants.HOME_PAGE_ACTION
即可。
@Entry
@Component
struct SuccessPage {
aboutToAppear() {
setTimeout(() => {
WindowModel.getInstance().destroySubWindow();
getContext(this).eventHub.emit(CommonConstants.HOME_PAGE_ACTION);
}, CommonConstants.LOGIN_WAIT_TIME);
}
总结:
1、在aboutToAppear里面使用EventHub 的on注册是一个事件
2、通过注册通过EventHub的emit方法发送对应的事件
参考资料:
EventHub官方文档
Demo地址