事情的起源
在做項(xiàng)目的過程中,遇到這么一個(gè)需求:輕按按鈕,事件觸發(fā)一次,長(zhǎng)按按鈕,則事件需要不停的觸發(fā),微信沒有提供這個(gè)方法,需要開發(fā)者自身去完成。
邏輯分析
當(dāng)按鈕按下, 此時(shí)獲取得到按下的時(shí)間戳和一個(gè)按鈕的狀態(tài), 寫入this.data里面, 寫入成功后, 開啟一個(gè)遞歸函數(shù), 首先是得到當(dāng)前時(shí)間戳, 取出開始的時(shí)間戳, 二者做對(duì)比, 當(dāng)大于設(shè)定值如200毫秒, 則為長(zhǎng)按時(shí)間, 若小于, 則為單擊事件, 當(dāng)按鈕松開, 改變按鈕狀態(tài), 清除計(jì)時(shí)器.
代碼實(shí)現(xiàn)
-
touchStart: function(e){
-
let timeStart = this.getTime();
-
let isTouch = true;
-
this.setData({timeStart, isTouch}, this.getNum)
-
}
-
-
touchEnd: function(){
-
this.setData({ isTouch: false }, this.getNum)
-
}
-
-
getNum: function(){
-
let { timeStart, isTouch } = this.data;
-
let timeNow = this.getTime();
-
let timeNum = 200;
-
let num = timeNow - timeStart;
-
let touchType = num < timeNum ? '單擊': '長(zhǎng)按';
-
if(isTouch){
-
// fnc 執(zhí)行想要做的事
-
this.timer = setTimeout(this.getNum, 100)
-
}
-
else{
-
clearTimeout(this.timer)
-
}
-
}
-
-
getTime: function(){
-
let time = new Date()
-
return time.getTime()
-
} //獲取當(dāng)前時(shí)間的毫秒數(shù)
微信小知識(shí)
this.setData為一個(gè)異步函數(shù), 如果有業(yè)務(wù)需要當(dāng)數(shù)據(jù)寫入成功后執(zhí)行的話,可以使用這個(gè)方法來執(zhí)行 this.setData({}, cb) cb 為回調(diào)函數(shù)
BUG修改
雖然按照以上情況能實(shí)現(xiàn)預(yù)期效果,但是還不夠完美,經(jīng)過實(shí)測(cè),當(dāng)快速點(diǎn)擊并松開(在100ms內(nèi)),想要執(zhí)行的函數(shù)并不會(huì)觸發(fā),為了能兼容這種情況,我做出了一點(diǎn)改變,添加了一個(gè)bindtap函數(shù),并在添加一個(gè)狀態(tài)來判斷是否觸發(fā)執(zhí)行函數(shù)
-
//bindtap 函數(shù)
-
tap: function(){
-
let { isSend } = this.data
-
if(!isSend){
-
// fnc 執(zhí)行函數(shù)
-
}
-
}
-
-
//getNum 做適應(yīng)性改變
-
getNum: function(){
-
let { timeStart, isTouch, isSend } = this.data;
-
let timeNow = this.getTime();
-
let timeNum = 200;
-
let num = timeNow - timeStart;
-
let touchType = num < timeNum ? '單擊': '長(zhǎng)按';
-
if(isTouch){
-
// fnc 執(zhí)行想要做的事
-
this.setData({isSend: true }) // 添加的代碼
-
this.timer = setTimeout(this.getNum, 100)
-
}
-
else{
-
clearTimeout(this.timer)
-
this.setData({ isSend:false }) //添加的代碼
-
}
-
}
-
//
因?yàn)樗接邢蓿荒芡ㄟ^這種方式來進(jìn)行修改,如果有更好的方法,歡迎提出意見和建議
|