使用了一段時(shí)間的ts,感覺(jué)使用js有點(diǎn)不順手;所以就找到了,來(lái)開(kāi)發(fā)微信小程序;
數(shù)據(jù)同步:
在下新建event.ts;(在src下新建一個(gè)的文件夾小程序js同步執(zhí)行,用于存放公共的方法);
class Event {
/**事件列表*/
private eventList = {};
/**
* 發(fā)送事件
* @type 事件類型
* @args 攜帶數(shù)據(jù)
*/
public sendEvent(type: string, ...args: any[]) {
let arr: Array = 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);
}
}
}
/**
* 監(jiān)聽(tīng)事件
* @type 事件類型
* @listener 回調(diào)函數(shù)
* @thisObject 回調(diào)執(zhí)行對(duì)象
*/
public addEvent(type: string, listener: Function, thisObject: any) {
let arr: Array = 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 回調(diào)函數(shù)
* @thisObject 回調(diào)執(zhí)行對(duì)象
*/
public removeEvent(type: string, listener: any, thisObject: any) {
let arr: Array = 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();
具體使用: 發(fā)布事件:
在你需要發(fā)布的頁(yè)面ts中引入event.ts;
import { $Event } from 'common/event';
比如說(shuō)在請(qǐng)求成功以后去發(fā)布事件;
$Event.sendEvent('like', { id: this.data.articalId });//這邊傳id
監(jiān)聽(tīng)事件:
在你需要的頁(yè)面ts中 引入event.ts
import { $Event } from 'common/event';
async onLoad(options:any){
? ? ? //監(jiān)聽(tīng)事件
? ? ? $Event.addEvent("like", (e: any) => {
? ? ? ? ? ? ?//取id的話就是e.id;
? ? ? ? ? ? ?this.setRecommendLike(e); //接收到參數(shù)進(jìn)行的操作;
? ? ? ?}, this);
}
移除監(jiān)聽(tīng)事件:
onUnload() {
$Event.removeEvent("like", (e: any) => { console.log(e, '移除監(jiān)聽(tīng)事件') }, this);
$Event.removeEvent("comment", (e: any) => { console.log(e, '移除監(jiān)聽(tīng)評(píng)論數(shù)量事件') }, this);
$Event.removeEvent("forward", (e: any) => { console.log(e, '移除監(jiān)聽(tīng)轉(zhuǎn)發(fā)數(shù)量事件') }, this);
$Event.removeEvent("fansCount", (e: any) => { console.log(e, '移除關(guān)注事件') }, this);
}
如有錯(cuò)誤小程序js同步執(zhí)行,請(qǐng)指正! 非常感謝!