wetoast.js
2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/**
* WeToast by kiinlam
* WeApp Toast add-ons
* 微信小程序toast增强插件
* Github: https://github.com/kiinlam/wetoast
* LICENSE: MIT
*/
function WeToastClass () {
//构造函数
function WeToast () {
let pages = getCurrentPages()
let curPage = pages[pages.length - 1]
this.__page = curPage
this.__timeout = null
//附加到page上,方便访问
curPage.wetoast = this
return this
}
//切换显示/隐藏
WeToast.prototype.toast = function(data) {
try {
if (!data) {
this.hide()
} else {
this.show(data)
}
} catch (err) {
// console.error(err)
// fail callback
data && typeof data.fail === 'function' && data.fail(data)
} finally {
// complete callback
data && typeof data.complete === 'function' && data.complete(data)
}
}
//显示
WeToast.prototype.show = function(data) {
let page = this.__page
clearTimeout(this.__timeout)
//display需要先设置为block之后,才能执行动画
page.setData({
'__wetoast__.reveal': true
})
setTimeout(()=>{
let animation = wx.createAnimation()
animation.opacity(1).step()
data.animationData = animation.export()
data.reveal = true
page.setData({
__wetoast__: data
})
},30)
if (data.duration === 0) {
// success callback after toast showed
setTimeout (() => {
typeof data.success === 'function' && data.success(data)
}, 430)
} else {
this.__timeout = setTimeout(() => {
this.toast()
// success callback
typeof data.success === 'function' && data.success(data)
}, (data.duration || 1500) + 400)
}
}
//隐藏
WeToast.prototype.hide = function() {
let page = this.__page
clearTimeout(this.__timeout)
if (!page.data.__wetoast__.reveal) {
return
}
let animation = wx.createAnimation()
animation.opacity(0).step()
page.setData({
'__wetoast__.animationData': animation.export()
})
setTimeout(() => {
page.setData({
__wetoast__: {'reveal': false}
})
}, 400)
}
return new WeToast()
}
module.exports = {
WeToast: WeToastClass
}