modal.js 2.58 KB
/**
 * Modal 模态组件
 *
 * @author: Aiden Xu<aiden.xu@yoho.cn>
 * @date: 2016/07/18
 */

'use strict';

const template = require('components/modal.hbs');

class Modal {
    /**
     * Modal
     *
     * @param opts
     */
    constructor(opts) {
        // 默认参数
        this.defaults = {
            isModal: true,
            template: template,
            title: '',
            text: '',
            buttons: [
                {
                    text: '好',
                    handler: () => {
                        this.hide();
                    }
                }
            ]
        };

        // 初始化参数
        this.settings = Object.assign({}, this.defaults, opts);
        const tpl = this.settings.template({
            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;

        this.elem.appendTo('body');

        // 事件绑定
        buttons.each(function(index) {
            $(this).click(self.settings.buttons[index].handler.bind(self));
        });
    }

    show() {
        // 显示覆盖层
        this.overlay = $.overlay({
            clickToClose: false
        });
        this.overlay.show();

        // 居中显示
        this.elem.css({
            left: ($(window).width() - this.elem.outerWidth()) / 2,
            top: ($(window).height() - this.elem.outerHeight()) / 2 + $(window).scrollTop()
        }).show().addClass('animation-target');
    }

    hide() {
        this.overlay.hide();
        this.elem.hide().remove();
    }
}

(function($) {
    $.modal = function(opts) {
        return new Modal(opts);
    };

    $.extend($.modal, {
        alert: (text, title)=> {
            const modal = $.modal({
                text: text,
                title: title
            });

            modal.show();
        },
        confirm: (text, title, callback)=> {
            const modal = $.modal({
                text: text,
                title: title,
                buttons: [
                    {
                        text: '取消',
                        handler: function() {
                            this.hide();
                        }
                    },
                    {
                        text: '好',
                        handler: callback || $.noop
                    }
                ]
            });

            modal.show();
        }
    });
}(jQuery));


module.exports = Modal;