适用于api11 和api12 废话不多说,直接上代码
import emitter from '@ohos.events.emitter';
import { StringUtils } from '@ohos/flutter_ohos';
export class EmitterUtils{
/**
* 发射字符串类型的
* @param eventId
* @param data
*/
public static sendEvent(eventId:string,data:string=''){
let eventData: emitter.EventData = {
data: {
"content": data,
}
};
let options: emitter.Options = {
priority: emitter.EventPriority.HIGH
};
emitter.emit(eventId, options, eventData);
}
/**
* 发送一个object ,并将eventId 带过去
* @param eventId
* @param data
*/
public static sendObjetEvent(eventId:string,data:object){
let eventData: emitter.EventData = {
data: {
"content": data,
"eventId":eventId
}
};
let options: emitter.Options = {
priority: emitter.EventPriority.HIGH
};
emitter.emit(eventId, options, eventData);
}
/**
* 监听string
* @param eventId
* @param onReceive
*/
public static listenString(eventId:string,onReceive:(content:string)=>void){
// 收到eventId为"eventId"的事件后执行回调函数
emitter.on(eventId, (data:emitter.EventData) => {
let content:string=data.data?.content;
if(StringUtils.isNotEmpty(content)){
onReceive(content)
}
});
}
/**
* 监听对象
* @param eventId
* @param onReceive
*/
public static listen(eventId:string,onReceive:(data:emitter.EventData)=>void){
// 收到eventId为"eventId"的事件后执行回调函数
emitter.on(eventId, (data:emitter.EventData) => {
onReceive(data)
});
}
/**
* 取消eventID的所有事件回调处理函数
* @param ventId
*/
public static closeEvent(ventId:string){
emitter.off(ventId);
}
}
发送字符类型
EmitterUtils.sendEvent(EmitterIdConstants.TAB_DASHBOARD_NO_TITLE_DATA,"noTitle")
接收字符串类型
EmitterUtils.listenString(EmitterIdConstants.TAB_DASHBOARD_NO_TITLE_DATA, (content: string) => {
if (StringUtils.isNotEmpty(content)) {
//...todo...
}
})
发送对象类型
let data= await this.fetchKnowledgeTitles();
let map = new Map<string, object>();
map.set("titleList", data ? data.result || [] : []);
EmitterUtils.sendObjetEvent(EmitterIdConstants.GET_TITLE_LIST,map)
接收对象类型
EmitterUtils.listen(EmitterIdConstants.GET_TITLE_LIST, (data: emitter.EventData) => {
if (data.data != null){
try {
let map = data.data?.content as Map<string, Object>
} catch (e) {
}
}
})
销毁这个订阅
aboutToDisappear(): void {
EmitterUtils.closeEvent(EmitterIdConstants.ON_HOME_TAB_CLICK)
}
上面 EmitterIdConstants 是你起的事件常量名字
export class EmitterIdConstants{
static readonly ON_HOME_TAB_CLICK = 'home_tab_click';
static readonly GET_TITLE_LIST = 'get_title_list'; //title List
........
}