DIV CSS 佈局教程網

自製 global.js 工具庫源碼分享(Dom / Event / Lang / Cookie)
編輯:關於JavaScript     

這是一份自己累積的前端工具庫,用命名空間把常用操作分門別類。它保留了那個年代處理跨瀏覽器差異的實作方式,同時也把「命名空間、get 包裝、擴充繼承、Cookie 封裝」這幾個通用套路示範得很完整。

命名空間機制

用字串路徑動態建立巢狀物件,避免全域污染:

var GLOBAL = {};
GLOBAL.namespace = function(str) {
  var arr = str.split("."), o = GLOBAL, i;
  for (i = (arr[0] = "GLOBAL") ? 1 : 0; i < arr.length; i++) {
    o[arr[i]] = o[arr[i]] || {};   // 已存在就沿用,否則建立
    o = o[arr[i]];
  }
};
GLOBAL.namespace("Dom");    // 此後就能用 GLOBAL.Dom.xxx

o[arr[i]] = o[arr[i]] || {} 這行是重點:讓同一個命名空間可以重複宣告而不會把先前掛上去的方法洗掉。

Dom 相關

// 取下一個「元素」節點(跳過空白文字節點)
GLOBAL.Dom.getNextNode = function (node) {
  node = typeof node == "string" ? document.getElementById(node) : node;
  var nextNode = node.nextSibling;
  if (!nextNode) { return null; }
  while (nextNode) {
    if (nextNode.nodeType == 1) { break; }
    nextNode = nextNode.nextSibling;
  }
  return nextNode;
};

// 設定透明度(IE 用 filter,標準瀏覽器用 opacity)
GLOBAL.Dom.setOpacity = function (node, level) {
  node = typeof node == "string" ? document.getElementById(node) : node;
  if (document.all) { node.style.filter = 'alpha(opacity=' + level + ')'; }
  else { node.style.opacity = level / 100; }
};

// 依類別名稱取得元素(在 querySelector 出現前的標準做法)
GLOBAL.Dom.getElementsByClassName = function (str, root, tag) {
  root = root ? (typeof root == "string" ? document.getElementById(root) : root) : document.body;
  tag  = tag || "*";
  var els = root.getElementsByTagName(tag), arr = [];
  for (var i = 0, n = els.length; i < n; i++) {
    var k = els[i].className.split(" "), l = k.length;
    for (var j = 0; j < l; j++) {
      if (k[j] == str) { arr.push(els[i]); break; }
    }
  }
  return arr;
};

// 同時接受 id 字串與元素參照的 get
GLOBAL.Dom.get = function (node) {
  return typeof node === "string" ? document.getElementById(node) : node;
};

typeof node == "string" ? document.getElementById(node) : node 這個「字串或元素都能收」的設計,讓所有工具函式都能被 $('id') 或 $(element) 兩種方式呼叫,是很實用的約定。

Event 相關

GLOBAL.Event.stopPropagation = function(e) {
  e = window.event || e;                     // 事件物件來源不同
  if (document.all) { e.cancelBubble = true; }
  else { e.stopPropagation(); }
};

GLOBAL.Event.getEventTarget = function(e) {
  e = window.event || e;
  return e.srcElement || e.target;           // 事件目標名稱也不同
};

GLOBAL.Event.on = function(node, eventType, handler) {
  node = typeof node == "string" ? document.getElementById(node) : node;
  if (document.all) { node.attachEvent("on" + eventType, handler); }   // IE:attachEvent
  else { node.addEventListener(eventType, handler, false); }           // 標準:addEventListener
};

這三個函式對應了當時最麻煩的三個相容性問題:事件物件怎麼拿、目標元素叫什麼名字、綁定用哪個 API。attachEvent 有個著名的副作用:回呼裡的 this 會指向 window 而非元素本身,且重複註冊同一個處理器會被執行多次。這也是後來大家改用 addEventListener 並搭配 bind 或箭頭函式的原因。

Lang 相關

GLOBAL.Lang.trim = function(ostr) { return ostr.replace(/^\s+|\s+$/g, ""); };
GLOBAL.Lang.isNumber = function(s) { return !isNaN(s); };

function isString(s)    { return typeof s === "string"; }
function isBoolean(s)   { return typeof s === "boolean"; }
function isFunction(s)  { return typeof s === "function"; }
function isNull(s)      { return s === null; }
function isUndefined(s) { return typeof s === "undefined"; }
function isEmpty(s)     { return /^\s*$/.test(s); }
function isArray(s)     { return s instanceof Array; }

// 原型式繼承
GLOBAL.Lang.extend = function(subClass, superClass) {
  var F = function() { };
  F.prototype = superClass.prototype;
  subClass.prototype = new F();
  subClass.prototype.constructor = subClass;
  subClass.superClass = subClass.prototype;
  if (superClass.prototype.constructor == Object.prototype.constructor) {
    superClass.prototype.constructor = superClass;
  }
};

這段繼承寫法是經典的「暫時建構子」技巧:用一個空的 F 當中介,讓子類原型繼承父類原型,卻不必呼叫父類建構子。ES6 有了 class 與 extends 之後,這整段都可以刪掉了。

Cookie 封裝

GLOBAL.Cookie = {
  read: function (name) {
    var cookieStr = ";" + document.cookie + ";";
    var index = cookieStr.indexOf(";" + name + "=");
    if (index != -1) {
      var s = cookieStr.substring(index + name.length + 3, cookieStr.length);
      return unescape(s.substring(0, s.indexOf(";")));
    }
    return null;
  },
  set: function (name, value, expires) {
    var expDate = new Date();
    expDate.setTime(expDate.getTime() + expires * 24 * 60 * 60 * 1000);  // 預設以天為單位
    document.cookie = name + "=" + escape(value) +
      ";expires=" + expDate.toGMTString() + ";path=/";
  },
  del: function (name) {
    if (this.read(name) != null) {
      var exp = new Date(new Date().getTime() - 1);
      document.cookie = name + "=;expires=" + exp.toGMTString() + ";path=/";
    }
  }
};

字串前後各補一個分號(";" + document.cookie + ";")是為了簡化比對——這樣每個 ;name= 的起點都對齊,不必額外處理第一項沒有前導分號的情況。

$ 的意義

function $(node) {
  return typeof node == "string" ? document.getElementById(node) : node;
}

它並不是 jQuery 專利,只是一個「id 或元素都能收」的縮寫約定,幾乎每個前中期工具庫都會有這麼一個。

這份庫今天該怎麼用

它如實記錄了那個「家家戶戶都要自己攤平瀏覽器差異」的時代。以現今的標準,幾乎每一段都有原生替代品:

  • Dom.getElementsByClassName → document.querySelectorAll('.cls')
  • Dom.setOpacity → 直接用 style.opacity(IE8 以下已不在支援範圍)
  • Event.on → addEventListener
  • Event.stopPropagation / getEventTarget → e.stopPropagation() / e.target
  • Lang.trim → String.prototype.trim()
  • Lang.extend → class extends 或 Object.assign
  • Cookie 讀寫 → 若非必要請改用 localStorage;確實需要 Cookie 時建議用成熟套件處理編碼與 path/domain/SameSite 細節

不過它的架構思路仍然值得學:用 namespace 分層、所有 DOM 入口都接受「id 或元素」、把相容性判斷集中在單一層(這樣要升級時只改一處)、Cookie 這類易錯的邏輯完整封裝起來。换成 ES Module 的 export,這套組織方式到現在還是好習慣。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved