简介
MBassador 是一个发布订阅模式的三方库
- 支持事件发布,订阅
- 支持同步异步发送事件
- 支持事件过滤
- 支持设置接收事件的强弱引用
- 支持事件注解驱动
下载安装
ohpm install @ohos/mbassador
注解
| 注解 | 功能 |
|---|
| @Handler | 事件接收处理程序 |
| @Listener | 可用于自定义侦听器范围的配置,如使用的引用类型 |
属性描述说明
@Handler
| Properties | Description |
|---|
| filters?: IMessageFilter[] | 事件过滤 |
| delivery?: Invoke | 事件同步异步发布 |
| priority?: number | 事件优先级 |
| enabled?: boolean | 事件是否接收 |
@Listener
| Properties | Description |
|---|
| className | 事件接收对象name |
| References | 强弱引用对象设置 |
使用说明
监听器
import { Annotations, References } from '@ohos/mbassador'
......
@Annotations.Listener("ExampleListener",References.Weak)
export class ExampleListener {
@Annotations.handle()
firstMessage(str: string, listener: ExampleListener) {
}
@Annotations.handle({priority:100000,enabled:false})
secondMessage(str: string, listener: ExampleListener) {
}
@Annotations.handle({filters:[new ExampleFilter],enabled:true})
thirdMessage(str: string, listener: ExampleListener) {
}
}
同步
let mbassador = new MBassador<String>()
let listener = new ExampleListener(callback)
mbassador.subscribe(listener);
mbassador.post(new String("this is first")).now();
异步
let mbassador:MBassador = new MBassador()
let listener:ExampleListener = new ExampleListener(callback)
mbassador.subscribe(listener);
mbassador.post(new String("this is asynchronously message")).asynchronously();
解绑
mbassador.unSubscribe(listener)
DD一下:欢迎大家关注工粽号<程序猿百晓生>,可以了解到以下知识点。
`欢迎大家关注工粽号<程序猿百晓生>,可以了解到以下知识点。`
1.OpenHarmony开发基础
2.OpenHarmony北向开发环境搭建
3.鸿蒙南向开发环境的搭建
4.鸿蒙生态应用开发白皮书V2.0 & V3.0
5.鸿蒙开发面试真题(含参考答案)
6.TypeScript入门学习手册
7.OpenHarmony 经典面试题(含参考答案)
8.OpenHarmony设备开发入门【最新版】
9.沉浸式剖析OpenHarmony源代码
10.系统定制指南
11.【OpenHarmony】Uboot 驱动加载流程
12.OpenHarmony构建系统--GN与子系统、部件、模块详解
13.ohos开机init启动流程
14.鸿蒙版性能优化指南
.......
过滤器
import { IMessageFilter, SubscriptionContext } from '@ohos/mbassador'
export class ExampleFilter implements IMessageFilter<String> {
accepts(msg: String, context: SubscriptionContext) {
return true;
}
}
目录结构
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|