loading.js 1.45 KB
/**
 * 加载组件
 *
 * @author: Aiden Xu <aiden.xu@yoho.cn>
 * @date: 2016/07/18
 */

'use strict';

const $ = require('yoho-jquery');
const Overlay = require('./overlay');
const template = require('components/loading.hbs');
const _ = require('lodash');
const AJAX_LOADING_ENABLED = false; // 全局控制

if (!Overlay) {
    throw new Error('Required dependency "Overlay" not found!');
}

class Loading {
    constructor(opts) {
        this.defaults = {};
        this.settings = Object.assign({}, this.defaults, opts);

        this.elem = $(template());
    }


    /**
     * 显示
     */
    show() {
        if (!this.isVisible) {
            this.isVisible = true;

            if (this.elem.parent().length === 0) {
                this.elem.appendTo('body');
            }

            this.overlay = new Overlay({
                animation: 'fade',
                clickToClose: false
            });
            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)();
    });
}

module.exports = instance;