bmfe-mina-template
Version:
BM 小程序模板
107 lines (96 loc) • 2.65 kB
JavaScript
// canSend 可发送
// sending 正在发送
// sended 已发送
// sendFail 发送失败
import wepy from 'wepy'
export default class V {
constructor({ cutDownTime = 60 } = {}) {
this.cutDownTime = cutDownTime
this.leftTime = cutDownTime
this.sendStatus = 'canSend'
this.sendType = ''
this._customEvents = {}
}
getCode(phone, type='SMS', channel=null) {
if(!phone) return
const info = this.getStatus()
if(info.sendStatus == 'canSend') {
this.sendType = type
this._setStatus('sending')
wepy.request({
url: '/mobile/mina/user/send/verifyCode',
data: {
phone,
type,
channel
}
}).then(res => {
this._setStatus('sended')
this._setCountDown()
}, ()=> {
this._resetStatus()
this.emit('requestError', res)
})
// setTimeout(() => {
// this._setStatus('sended')
// this._setCountDown()
// }, 1000)
}
// else {
// this.emit('statusChange', info)
// }
}
getStatus() {
return {
sendStatus: this.sendStatus,
sendType: this.sendType,
leftTime: this.leftTime,
cutDownTime: this.cutDownTime
}
}
_setCountDown() {
this._cutDownTime()
this._clearTimer()
this.timer = setInterval(() => {
if(this.leftTime < 1) {
this._clearTimer()
this._resetStatus()
} else {
this._cutDownTime()
}
}, 1000)
}
_cutDownTime() {
this.leftTime--
this.emit('timeChange', this.getStatus())
}
_resetStatus() {
this.sendType = ''
this.leftTime = this.cutDownTime
this._setStatus('canSend')
}
_setStatus(type) {
this.sendStatus = type
this.emit('statusChange', this.getStatus())
}
_clearTimer() {
this.timer && clearInterval(this.timer)
this.timer = null
}
emit(type, data) {
if(this._customEvents[type]) {
this._customEvents[type].forEach(fn => {
fn.call(this, data)
})
}
}
on(type, fn) {
if(!this._customEvents[type]) {
this._customEvents[type] = []
}
this._customEvents[type].push(fn)
}
removeCustoms() {
this._customEvents = {}
}
}