loading.js 2.04 KB
/**
 * 加载组件
 *
 * @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;