整理多年專案萃取的輕量工具庫,採用命名空間模組化,涵蓋 DOM 操作、事件綁定、型別判斷、字串處理、Cookie 管理等高頻功能,無第三方依賴,壓縮後約 3KB。
var GLOBAL = {};
GLOBAL.namespace = function(ns) {
var parts = ns.split('.'), obj = GLOBAL, i = (parts[0] === 'GLOBAL') ? 1 : 0;
for (; i < parts.length; i++) {
obj[parts[i]] = obj[parts[i]] || {};
obj = obj[parts[i]];
}
};
<script src="global.js"></script>
<script>
GLOBAL.namespace('MyApp.Utils');
MyApp.Utils.formatDate = function(d) { ... };
// DOM
var btn = GLOBAL.Dom.get('submitBtn');
GLOBAL.Event.on(btn, 'click', function(e) {
var target = GLOBAL.Event.getEventTarget(e);
GLOBAL.Dom.setOpacity(target, 50);
});
// Cookie
GLOBAL.Cookie.set('token', 'abc123', 7); // 7 天
var token = GLOBAL.Cookie.get('token');
var GLOBAL = {};
GLOBAL.namespace = function(str) { ... };
// Dom
GLOBAL.namespace('Dom');
GLOBAL.Dom.get = function(node) { ... };
GLOBAL.Dom.getNextNode = function(node) { ... };
GLOBAL.Dom.setOpacity = function(node, level) { ... };
GLOBAL.Dom.getElementsByClassName = function(str, root, tag) { ... };
// Event
GLOBAL.namespace('Event');
GLOBAL.Event.stopPropagation = function(e) { ... };
GLOBAL.Event.getEventTarget = function(e) { ... };
GLOBAL.Event.on = function(node, eventType, handler) { ... };
// Lang
GLOBAL.namespace('Lang');
GLOBAL.Lang.trim = function(ostr) { return ostr.replace(/^\s+|\s+$/g, ''); };
GLOBAL.Lang.isNumber = function(s) { return !isNaN(s); };
// isString, isBoolean, isFunction, isNull, isUndefined, isEmpty, isArray ...
GLOBAL.Lang.extend = function(subClass, superClass) {
var F = function(){}; F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
subClass.superclass = superClass.prototype;
};
// 便捷別名
function $(node) { return GLOBAL.Dom.get(node); }