使用minapp 的小程序全局数据同步问题

使用了一段时间的ts,感觉使用js有点不顺手;所以就找到了minapp,来开发微信小程序;

数据同步:

在common下新建event.ts;(在src下新建一个common的文件夹,用于存放公共的方法);

class Event {
	/**事件列表*/
	private eventList = <any>{};

    /**
     * 发送事件
     * @type 事件类型
     * @args 携带数据
     */
	public sendEvent(type: string, ...args: any[]) {
		let arr: Array<any> = this.eventList[type];
		if (arr != null) {
			let len = arr.length;
			let listen: Function;
			let thisObject: any;
			for (let i = 0; i < len; i++) {
				let msg = arr[i];
				listen = msg[0];
				thisObject = msg[1];
				listen.apply(thisObject, args);
			}
		}
	}

    /**
     * 监听事件
     * @type 事件类型
     * @listener 回调函数
     * @thisObject 回调执行对象
     */
	public addEvent(type: string, listener: Function, thisObject: any) {
		let arr: Array<any> = this.eventList[type];
		if (arr == null) {
			arr = [];
			this.eventList[type] = arr;
		} else {
			let len = arr.length;
			for (let i = 0; i < len; i++) {
				if (arr[i][0] == listener && arr[i][1] == thisObject) {
					return;
				}
			}
		arr.push([listener, thisObject]);
	}

    /**
     * 移除事件
     * @type 事件类型
     * @listener 回调函数
     * @thisObject 回调执行对象
     */
	public removeEvent(type: string, listener: any, thisObject: any) {
		let arr: Array<any> = this.eventList[type];
		if (arr != null) {
			let len = arr.length;
			for (let i = len - 1; i >= 0; i--) {
				if (arr[i][0] == listener && arr[i][1] == thisObject) {
					arr.splice(i, 1);
				}
			}
		if (arr && arr.length == 0) {
			this.eventList[type] = null;
			delete this.eventList[type];
		}
	}
}

export const $Event = new Event();

具体使用:

发布事件:

在你需要发布的页面ts中引入event.ts;

import { $Event } from 'common/event';

比如说在请求成功以后去发布事件;

$Event.sendEvent('like', { id: this.data.articalId });//这边传id

监听事件:

在你需要的页面ts中 引入event.ts

import { $Event } from 'common/event';



async onLoad(options:any){

      //监听事件

      $Event.addEvent("like", (e: any) => {

             //取id的话就是e.id;

             this.setRecommendLike(e); //接收到参数进行的操作;

       }, this);

}

 移除监听事件:

onUnload() {
	$Event.removeEvent("like", (e: any) => { console.log(e, '移除监听事件') }, this);
	$Event.removeEvent("comment", (e: any) => { console.log(e, '移除监听评论数量事件') }, this);
	$Event.removeEvent("forward", (e: any) => { console.log(e, '移除监听转发数量事件') }, this);
	$Event.removeEvent("fansCount", (e: any) => { console.log(e, '移除关注事件') }, this);
}

 如有错误,请指正! 非常感谢!

猜你喜欢

转载自blog.csdn.net/weixin_42049536/article/details/85320215