modal.js 2.28 KB
/**
 * 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;