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