layui.js layui 源碼 分析 欄目 JavaScript 简体版
原文   原文鏈接
 
/*!

 @Title: Layui
 @Description:經典模塊化前端框架
 @Site: www.layui.com
 @Author: 賢心
 @License:MIT

 */

;!function(win) {

    "use strict";

    var Lay = function() {
        this.v = '1.0.9_rls'; //版本號
    };

    Lay.fn = Lay.prototype;

    var doc = document,
        config = Lay.fn.cache = {},

        // 獲取本js所在目錄
        getPath = function() {
            var js = doc.scripts,
                jsPath = js[js.length - 1].src;
            return jsPath.substring(0, jsPath.lastIndexOf('/') + 1);
        }(),

        // 異常提示
        error = function(msg) {
            win.console && console.error && console.error('Layui hint: ' + msg);
        },

        // 檢測opera環境
        isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',

        // 內置模塊
        modules = {
            layer : 'modules/layer', //彈層
            laydate : 'modules/laydate', //日期
            laypage : 'modules/laypage', //分頁
            laytpl : 'modules/laytpl', //模板引擎
            layim : 'modules/layim', //web通信
            layedit : 'modules/layedit', //富文本編輯器
            form : 'modules/form', //表單集
            upload : 'modules/upload', //上傳
            tree : 'modules/tree', //樹結構
            table : 'modules/table', //富表格
            element : 'modules/element', //經常使用元素操做
            util : 'modules/util', //工具塊
            flow : 'modules/flow', //流加載
            carousel : 'modules/carousel', //輪播
            code : 'modules/code', //代碼修飾器
            jquery : 'modules/jquery', //DOM庫(第三方)  
            mobile : 'modules/mobile', //移動大模塊 | 若當前爲開發目錄,則爲移動模塊入口,不然爲移動模塊集合
            'layui.all' : 'dest/layui.all' //PC模塊合併版
        };

    config.modules = {}; //記錄模塊物理路徑
    config.status = {}; // 記錄已註冊的模塊集。
    config.timeout = 10; //符合規範的模塊請求最長等待秒數
    config.event = {}; //記錄模塊自定義事件

    // 定義模塊
    Lay.fn.define = function(deps, callback) {
        var that = this,
            type = typeof deps === 'function',
            mods = function() {
                // 參數callback,可選,用於回調。
                // 回調參數function,用於回調時,註冊模塊。
                typeof callback === 'function' && callback(function(app, exports) {
                    // 回調參數function的參數app,必要,表明模塊名。
                    // 回調參數function的參數exports,必要,表明模塊的接口方法。
                    layui[app] = exports;
                    // config.status,記錄已註冊的模塊集。
                    config.status[app] = true;
                });
                return this;
            };

        // 參數deps,表明依賴的模塊集,可選。
        type && (
            callback = deps,
            deps = []
        );

        // 至關於layui['layui.all'] || layui['layui.mobile']
        // 模塊名layui.all,表明全部模塊。
        // 模塊名layui.mobile,表明手機版的全部模塊。
        // 若是已經加載全部模塊,則直接執行回調。
        if (layui['layui.all'] || (!layui['layui.all'] && layui['layui.mobile'])) {
            return mods.call(that);
        }

        // 方法layui.use,動態加載所依賴的模塊集deps。
        that.use(deps, mods);
        return that;
    };

    // 動態加載模塊集
    Lay.fn.use = function(apps, callback, exports) {
        var that = this,
        // config.dir,內置文件的基目錄,默認值爲layui.js的所在目錄,需以斜槓結束。
            dir = config.dir = config.dir ? config.dir : getPath;
        var head = doc.getElementsByTagName('head')[0];

        // 參數apps,必要,能夠是字符串或數組。
        apps = typeof apps === 'string' ? [ apps ] : apps;

        // 參數apps中存在jquery時,若是頁面已加載jQuery1.7+庫,則直接使用該庫。
        if (window.jQuery && jQuery.fn.on) {
            that.each(apps, function(index, item) {
                if (item === 'jquery') {
                    apps.splice(index, 1);
                }
            });
            layui.jquery = jQuery;
        }

        var item = apps[0],
            timeout = 0;
        // 參數exports,可選。
        exports = exports || [];

        // config.host,格式爲「//.../」,默認值爲config.dir中的主機,或當前頁面的主機。
        config.host = config.host || (dir.match(/\/\/([\s\S]+?)\//)/* 匹配「//.../」 */ || [ '//' + location.host + '/' ])[0];

        // apps.length === 0 || (layui['layui.all'] || layui['layui.mobile']) && modules[item]
        // 參數apps,容許爲空集。
        // 若是須要加載的模塊集爲空集,則執行回調。
        // 模塊名layui.all,表明全部模塊。
        // 模塊名layui.mobile,表明手機版的全部模塊。
        // modules,表明layui的內置模塊集。
        // 若是已經加載全部模塊,而且當前模塊是layui的內置模塊,則當前模塊不須要加載。
        if (apps.length === 0
            || (layui['layui.all'] && modules[item])
            || (!layui['layui.all'] && layui['layui.mobile'] && modules[item])
        ) {
            return onCallback(), that;
        }

        // 用於監聽文件加載完畢
        function onScriptLoad(e, url) {
            var readyRegExp = navigator.platform === 'PLaySTATION 3' ? /^complete$/ : /^(complete|loaded)$/
            if (e.type === 'load' || (readyRegExp.test((e.currentTarget || e.srcElement).readyState))) {
                config.modules[item] = url;
                head.removeChild(node);
                // 輪詢查看當前模塊是否已註冊,每0.025秒輪詢一次,共論詢config.timeout秒。
                // config.timeout,文件加載超時,默認值爲10秒。
                (function poll() {
                    if (++timeout > config.timeout * 1000 / 4) {
                        return error(item + ' is not a valid module');
                    };
                    config.status[item] ? onCallback() : setTimeout(poll, 4);
                }());
            }
        }

        var node = doc.createElement('script'),
        // config.base,表明擴展模塊的JS文件目錄,默認值爲空串,須要以斜槓結束。
        // modules,表明layui的內置模塊集。
        // layui.modules[name],表明模塊name的相對路徑(不包括後綴.js),默認值爲name。
        //         若是當前模塊是內置模塊,則相對路徑相對於config.dir + "lay/"。
        //        若是當前模塊是擴展模塊,則相對路徑相對於config.base。
            url = (modules[item] ? (dir + 'lay/') : (config.base || '')) + (that.modules[item] || item) + '.js';
        node.async = true;
        node.charset = 'utf-8';
        node.src = url + function() {
            // config.version=true時,使用config.v做爲版本號,不然本身做爲版本號,默認值不啓用版本號。
            // config.v,表明版本號,默認值爲當前時間。
            // config.version=true,config.v不設置時,使流覽器不會加載緩存文件,而是從新加載。
            var version = config.version === true ? (config.v || (new Date()).getTime()) : (config.version || '');
            return version ? ('?v=' + version) : '';
        }();

        // config.modules[name],表明已加載,或正在加載中的模塊name的相對路徑(不包括後綴.js)。
        if (!config.modules[item]) {
            head.appendChild(node);
            if (node.attachEvent && !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && !isOpera) {
                node.attachEvent('onreadystatechange', function(e) {
                    onScriptLoad(e, url);
                });
            } else {
                node.addEventListener('load', function(e) {
                    onScriptLoad(e, url);
                }, false);
            }
        } else {
            // 輪詢查看是否加載完畢,每0.025秒輪詢一次,共論詢config.timeout秒。
            // config.timeout,文件加載超時,默認值爲10秒。
            (function poll() {
                if (++timeout > config.timeout * 1000 / 4) {
                    return error(item + ' is not a valid module');
                };
                // config.status,記錄已註冊的模塊集。
                (typeof config.modules[item] === 'string' && config.status[item]) ? onCallback() : setTimeout(poll, 4);
            }());
        }
        config.modules[item] = url;

        //回調
        function onCallback() {
            // 參數exports,記錄模塊的接口。
            exports.push(layui[item]);
            // 加載下一個模塊,若是沒有下一個,則執行回調。
            apps.length > 1 ? that.use(apps.slice(1), callback, exports) : (typeof callback === 'function' && callback.apply(layui, exports));
        }

        return that;

    };

    // 獲取節點的style屬性值
    Lay.fn.getStyle = function(node, name) {
        var style = node.currentStyle ? node.currentStyle : win.getComputedStyle(node, null);
        return style[style.getPropertyValue ? 'getPropertyValue' : 'getAttribute'](name);
    };

    // 動態加載CSS
    Lay.fn.link = function(href, fn, cssname) {
        var that = this,
            link = doc.createElement('link');
        var head = doc.getElementsByTagName('head')[0];
        
        // 參數fn,可選。
        if (typeof fn === 'string')
            cssname = fn;
        
        // 參數cssname,用於標識CSS文件的ID,默認值爲href。
        var app = (cssname || href).replace(/\.|\//g, '');
        var id = link.id = 'layuicss-' + app,
            timeout = 0;

        link.rel = 'stylesheet';
        // config.debug=true時,使流覽器不會加載緩存文件。
        link.href = href + (config.debug ? '?v=' + new Date().getTime() : '');
        link.media = 'all';

        // 參數cssname,同一ID的CSS文件的只許加載一次。
        if (!doc.getElementById(id)) {
            head.appendChild(link);
        }

        // 參數fn,用於監聽CSS加載完畢。
        if (typeof fn !== 'function') return;
        // 輪詢查看是否加載完畢,每0.1秒輪詢一次,共論詢config.timeout秒。
        (function poll() {
            if (++timeout > config.timeout * 1000 / 100) {
                return error(href + ' timeout');
            };
            parseInt(that.getStyle(doc.getElementById(id), 'width')) === 1989 ? function() {
                fn();
            }() : setTimeout(poll, 100);
        }());
    };

    // css內部加載器
    Lay.fn.addcss = function(firename, fn, cssname) {
        // 全局配置dir,用於內置文件的基目錄,默認值爲layui.js所在的目錄,須要以斜槓結束。
        layui.link(config.dir + 'css/' + firename, fn, cssname);
    };

    // 圖片預加載
    Lay.fn.img = function(url, callback, error) {
        var img = new Image();
        img.src = url;
        if (img.complete) {
            return callback(img);
        }
        img.onload = function() {
            img.onload = null;
            callback(img);
        };
        img.onerror = function(e) {
            img.onerror = null;
            error(e);
        };
    };

    // 全局配置
    Lay.fn.config = function(options) {
        options = options || {};
        for (var key in options) {
            config[key] = options[key];
        }
        return this;
    };

    // layui.modules[name],表明模塊name的相對路徑(不包括後綴.js),默認值爲name。
    Lay.fn.modules = function() {
        var clone = {};
        for (var o in modules) {
            clone[o] = modules[o];
        }
        return clone;
    }();

    // 設置模塊的相對路徑(不含後綴.js)
    Lay.fn.extend = function(options) {
        var that = this;

        options = options || {};
        for (var o in options) {
            // layui[name],若是存在,則表示模塊name已註冊。
            // layui.modules[name],表明模塊name的相對路徑(不包括後綴.js),默認值爲name。
            // 已註冊或已設置相對路徑的模塊集,不容許再設置相對路徑。顯然,內置模塊的相對路徑不容許更改。
            if (that[o] || that.modules[o]) {
                error('\u6A21\u5757\u540D ' + o + ' \u5DF2\u88AB\u5360\u7528');
            } else {
                that.modules[o] = options[o];
            }
        }
        return that;
    };

    // 路由
    Lay.fn.router = function(hash) {
        var hashs = (hash || location.hash).replace(/^#/, '').split('/') || [];
        var item,
            param = {
                dir : []
            };
        for (var i = 0; i < hashs.length; i++) {
            item = hashs[i].split('=');
            /^\w+=/.test(hashs[i]) ? function() {
                if (item[0] !== 'dir') {
                    param[item[0]] = item[1];
                }
            }() : param.dir.push(hashs[i]);
            item = null;
        }
        return param;
    };

    // 本地存儲
    Lay.fn.data = function(table, settings) {
        table = table || 'layui';

        if (!win.JSON || !win.JSON.parse) return;

        //若是settings爲null,則刪除表
        if (settings === null) {
            return delete localStorage[table];
        }

        settings = typeof settings === 'object'
            ? settings
            : {
                key : settings
            };

        try {
            var data = JSON.parse(localStorage[table]);
        } catch (e) {
            var data = {};
        }

        if (settings.value)
            data[settings.key] = settings.value;
        if (settings.remove)
            delete data[settings.key];
        localStorage[table] = JSON.stringify(data);

        return settings.key ? data[settings.key] : data;
    };

    // 設備信息
    Lay.fn.device = function(key) {
        var agent = navigator.userAgent.toLowerCase();

        //獲取版本號
        var getVersion = function(label) {
            var exp = new RegExp(label + '/([^\\s\\_\\-]+)');
            label = (agent.match(exp) || [])[1];
            return label || false;
        };

        var result = {
            os : function() { //底層操做系統
                if (/windows/.test(agent)) {
                    return 'windows';
                } else if (/linux/.test(agent)) {
                    return 'linux';
                } else if (/iphone|ipod|ipad|ios/.test(agent)) {
                    return 'ios';
                }
            }(),
            ie : function() { //ie版本
                return (!!win.ActiveXObject || "ActiveXObject" in win) ? (
                    (agent.match(/msie\s(\d+)/) || [])[1] || '11' //因爲ie11並無msie的標識
                    ) : false;
            }(),
            weixin : getVersion('micromessenger') //是否微信
        };

        //任意的key
        if (key && !result[key]) {
            result[key] = getVersion(key);
        }

        //移動設備
        result.android = /android/.test(agent);
        result.ios = result.os === 'ios';

        return result;
    };

    // 提示
    Lay.fn.hint = function() {
        return {
            error : error
        }
    };

    // 遍歷
    Lay.fn.each = function(obj, fn) {
        var that = this,
            key;
        if (typeof fn !== 'function') return that;
        obj = obj || [];
        if (obj.constructor === Object) {
            for (key in obj) {
                if (fn.call(obj[key], key, obj[key])) break;
            }
        } else {
            for (key = 0; key < obj.length; key++) {
                if (fn.call(obj[key], key, obj[key])) break;
            }
        }
        return that;
    };

    // 阻止事件冒泡
    Lay.fn.stope = function(e) {
        e = e || win.event;
        e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
    };

    // 自定義模塊事件
    Lay.fn.onevent = function(modName, events, callback) {
        if (typeof modName !== 'string'
            || typeof callback !== 'function') return this;
        config.event[modName + '.' + events] = [ callback ];

        //再也不對屢次事件監聽作支持
        /*
        config.event[modName + '.' + events] 
          ? config.event[modName + '.' + events].push(callback) 
        : config.event[modName + '.' + events] = [callback];
        */

        return this;
    };

    // 執行自定義模塊事件
    Lay.fn.event = function(modName, events, params) {
        var that = this,
            result = null,
            filter = events.match(/\(.*\)$/) || []; //提取事件過濾器
        var set = (events = modName + '.' + events).replace(filter, ''); //獲取事件本體名
        var callback = function(_, item) {
            var res = item && item.call(that, params);
            res === false && result === null && (result = false);
        };
        layui.each(config.event[set], callback);
        filter[0] && layui.each(config.event[events], callback); //執行過濾器中的事件
        return result;
    };

    win.layui = new Lay();

}(window);
相關文章
相關標籤/搜索
每日一句
    每一个你不满意的现在,都有一个你没有努力的曾经。
本站公眾號
   歡迎關注本站公眾號,獲取更多信息