loading.js
2.04 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
/**
* 加载组件
*
* @author: Aiden Xu <aiden.xu@yoho.cn>
* @date: 2016/07/18
*/
'use strict';
import $ from 'jquery';
import Overlay from './overlay';
import template from 'components/loading.hbs';
const AJAX_LOADING_ENABLED = false; // 全局控制
if (!Overlay) {
throw new Error('Required dependency "Overlay" not found!');
}
/**
* 创建一个无抖动的函数
* @param {[type]} func [description]
* @param {[type]} wait [description]
* @param {[type]} immediate [description]
* @return {[type]}
*/
function debounce(func, wait, immediate) {
let timeout;
return function() {
let context = this, args = arguments;
let later = function() {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
};
let callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
}
class Loading {
constructor(opts) {
this.defaults = {};
this.settings = Object.assign({}, this.defaults, opts);
this.elem = $(template());
this.overlay = new Overlay({
animation: 'fade',
clickToClose: false
});
}
/**
* 显示
*/
show() {
if (!this.isVisible) {
this.isVisible = true;
if (this.elem.parent().length === 0) {
this.elem.appendTo('body');
}
this.overlay.show();
}
}
/**
* 关闭
*/
hide() {
if (this.isVisible) {
this.overlay.hide();
this.elem.detach();
this.isVisible = false;
}
}
}
const instance = new Loading();
if (AJAX_LOADING_ENABLED) {
$(document).ajaxStart(()=> {
debounce(()=> {
instance.show();
}, 100)();
});
$(document).ajaxStop(()=> {
debounce(()=> {
instance.hide();
}, 500)();
});
}
export default instance;