dialog.js 2.42 KB
/*
 * @Description: dialog
 * @Time: 2015/11/18
 * @author: chenglong.wang
 */

var $ = require('jquery'),
    Handlebars = require('yoho.handlebars'),
    Hammer = require('yoho.hammer');

var $dialogWrapper,
    dialogTpl,
    dialogTemplate;


dialogTpl = '<div id="dialog-wrapper" class="dialog-wrapper">' +
                '<div class="dialog-box">' +
                    '{{# hasHeader}}' +
                    '{{/ hasHeader}}' +
                    '<div class="dialog-content">{{dialogText}}</div>' +
                    '{{# hasFooter}}' +
                    '<div class="dialog-footer">' +
                    '{{# leftBtnText}}' +
                    '<span class="dialog-left-btn">{{.}}</span>' +
                    '{{/ leftBtnText}}' +
                    '{{# rightBtnText}}' +
                    '<span class="dialog-right-btn">{{.}}</span>' +
                    '{{/ rightBtnText}}' +
                    '</div>' +
                    '{{/ hasFooter}}' +
                '</div>' +
            '</div>';

dialogTemplate = Handlebars.compile(dialogTpl);

exports.showDialog = function(data, callback, callbackForLeft) {

    var dialogStr = dialogTemplate(data),
        $dialogBox,
        defaultHideDuraton,
        dialogWrapperHammer;

    $('.dialog-wrapper').remove();

    $('body').append($(dialogStr));

    $dialogBox = $('.dialog-box');
    $dialogWrapper = $('.dialog-wrapper');
    dialogWrapperHammer = new Hammer(document.getElementById('dialog-wrapper'));

    // 显示
    if (data.fast) {
        $dialogWrapper.css({
            display: 'block'
        });
    } else {
        $dialogWrapper.fadeIn();
    }

    $dialogBox.css({
        top: '50%',
        marginTop: -($dialogBox.height() / 2)
    });

    //隐藏
    if (data.autoHide) {
        defaultHideDuraton = 1000;
        if (data.autoHide > 1) {
            defaultHideDuraton = data.autoHide;
        }
        setTimeout(function() {
            $dialogWrapper.fadeOut();
        }, defaultHideDuraton);
    }

    dialogWrapperHammer.on('tap', function(event) {

        if ($(event.target).hasClass('dialog-left-btn')) {
            if (typeof callbackForLeft === 'function') {
                callbackForLeft();
            }
            $dialogWrapper.fadeOut();
        } else if ($(event.target).hasClass('dialog-right-btn')) {
            callback();
        }
    });
};