modal.js
2.28 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
/**
* Modal 模态组件
*
* @author: Aiden Xu<aiden.xu@yoho.cn>
* @date: 2016/07/18
*/
'use strict';
const $ = require('yoho-jquery');
const template = require('components/modal.hbs');
const Overlay = require('./overlay');
class Modal {
/**
* Modal
*
* @param opts
*/
constructor(opts) {
// 默认参数
this.defaults = {
isModal: true,
template: template,
styleClass: '',
title: '',
text: '',
buttons: [{
text: '好',
handler: () => {
this.hide();
}
}]
};
// 初始化参数
this.settings = Object.assign({}, this.defaults, opts);
const tpl = this.settings.template({
styleClass: this.settings.styleClass,
title: this.settings.title,
text: this.settings.text,
buttons: this.settings.buttons
});
// 生成模版
this.elem = $(tpl);
const buttons = this.elem.find('.button-group').children();
const self = this;
// 事件绑定
buttons.each(function(index) {
$(this).click(self.settings.buttons[index].handler.bind(self));
});
// 覆盖层
this.overlay = new Overlay({
clickToClose: false
});
}
show() {
this.overlay.show();
if (this.elem.parent().length === 0) {
this.elem.appendTo('body');
}
// 居中显示
this.elem.show().addClass('animation-target');
}
hide() {
this.overlay.hide();
this.elem.detach();
}
}
Object.assign(Modal, {
alert: (text, title) => {
const modal = new Modal({
text: text,
title: title
});
modal.show();
},
confirm: (text, title, callback) => {
const modal = new Modal({
text: text,
title: title,
buttons: [{
text: '取消',
handler: function() {
this.hide();
}
}, {
text: '好',
handler: callback || $.noop
}]
});
modal.show();
}
});
module.exports = Modal;