JavaScript 能做的事越來越多,伴隨而來的問題就是程式碼量暴增。當一份 .js 檔案膨脹到幾百行、每個功能各自綁一堆事件時,最痛苦的不是寫,而是「這個按鈕的事件到底在哪裡綁的」。
我採用了一個仿面向对象語言的做法:模仿「建構子自動執行」的概念,把所有事件綁定與初始化邏輯,以「註冊」的形式收攏到一個物件裡,再由一個 init 統一啟動。這樣整個頁面的行為就有了單一入口,可讀性與可維護性都明顯改善。
/**
* @version $Id$
* @author xjiujiu <xjiujiu@foxmail.com>
* @description HHJsLib Framework Apps
* @copyright Copyright (c) 2011-2012 https://www.xjiujiu.com. All right reserved
*/
HHJsLib.register({
// 相當於建構子:所有綁定集中在此,一眼看出這個頁面有哪些互動
init: function () {
this.bindPreviewBtn();
this.bindUploadEleImageBtn();
this.bindUploadEleAudioBtn('a.audio-upload-btn');
this.bindUploadEleVideoBtn('a.video-upload-btn');
this.bindDownloadEleAudioBtn();
this.bindNewConBtn();
this.bindDelConBtn('a.btn-del-con');
this.bindDelItemBtn('a.btn-del-item');
this.bindNewItemBoxClose('div.item-box');
this.bindPlusBtn('a.btn-plus');
this.bindAppendNewElement('div.new-item-box ul li a');
this.bindSetPreviewVideo();
this.bindAddAnswerBtn('a.btn-add-answer');
this.bindDelAnswerBtn('a.btn-del-answer');
this.bindDelImageBtn('a.btn-del-image');
this.bindDelAudioBtn('a.btn-del-audio');
this.initPlusBtn();
},
// 取得時間戳作為動態元素的唯一識別碼
getTimestamp: function () {
return (new Date()).getTime();
},
// 以樣板字串產生新的元素片段
initItemTplByType: function (type, t, heading) {
var itemHtml = eleTplMap[type].replace(/{t}/g, t);
itemHtml = itemHtml.replace(/{sort_num}/g, this.getNewEleSortNum(heading));
return itemHtml.replace(/{headingId}/g, heading);
},
// 把元素包進左右交錯的容器樣板
initItemBoxTpl: function (content, heading, t, side, type) {
var itemBoxHtml = eleTplMap.itemBox.replace(/{t}/g, t);
itemBoxHtml = itemBoxHtml.replace(/{headingId}/g, heading);
itemBoxHtml = itemBoxHtml.replace(/{side}/g, side);
itemBoxHtml = itemBoxHtml.replace(/{content}/g, content);
itemBoxHtml = itemBoxHtml.replace(/{hash}/g, hex_md5(t));
itemBoxHtml += '<div class="clearfix" id="clearfix-' + heading + '"></div>';
return itemBoxHtml.replace(/{type}/g, type);
},
// 新增元素後,把「+」按鈕移到正確位置並重綁事件
movePlusBtnBox: function (heading) {
$('#new-item-box-' + heading).remove();
var plusBtnHtml = eleTplMap.plusBtn.replace(/{headingId}/g, heading);
$(plusBtnHtml).insertBefore('#clearfix-' + heading);
var $items = $('#ele-part-box-' + heading).find('div.item-ele-box');
// 只有一個元素時,隱藏刪除鈕(至少要留一個)
if ($items.length < 2) {
$($items[0]).find('a.btn-del-item').hide();
} else {
$($items[0]).find('a.btn-del-item').show();
}
this.bindAppendNewElement('#new-item-box-' + heading + " ul.new-item-list-box li a");
this.bindPlusBtn('#btn-plus-' + heading);
},
// 刪除後重新排序左右交錯的版面
reArrangeItem: function (heading) {
var rank = 1;
$('#ele-part-box-' + heading).find('div.item-ele-box').each(function () {
if (rank % 2 === 0) {
$(this).removeClass('pull-left item-left').addClass('pull-right item-right');
} else {
$(this).removeClass('pull-right item-right').addClass('pull-left item-left');
}
rank++;
});
},
// 取得下一個排序號
getNewEleSortNum: function (heading) {
return parseInt(this.getMaxSortNum(heading)) + 1;
},
getMaxSortNum: function (heading) {
var sortNums = [];
$('.ele-sort-' + heading).each(function () {
sortNums.push($(this).val());
});
sortNums = sortNums.sort(function (a, b) {
if (a === b) { return 0; }
if (typeof a === typeof b) { return a > b ? -1 : 1; }
return typeof a > typeof b ? -1 : 1;
});
return sortNums[0] == null ? 0 : sortNums[0];
},
// 上傳圖片的通用流程:彈窗 → 選擇檔案 → 上傳 → 回填預覽
bindUploadModal: function (dom) {
var self = this;
$(dom).unbind('click').click(function () {
var $this = $(this);
var t = HHJsLib.modal.confirm(
'上傳圖片',
'<div class="text-center">' +
' <p>瀏覽您電腦裡的圖片,從中選擇一張。</p>' +
'<div class="btn-box btn btn-blue">' +
' <div id="upload-btn">從電腦上傳</div>' +
' </div>' +
' </div>'
);
var uploader = HJZUploader.createImage('#upload-btn', {
formData: { model: 'timeline' }
}, function (response) {
if (false == response.rs) {
self.setDemoBoxInit($this);
return HHJsLib.warn(response.message);
}
var imgHtml = '<img src="' + siteUrl + response.data.src + '" alt="' + response.data.name + '" />';
$($this.attr('data-demo-box')).html(imgHtml).show();
$($this.attr('data-field')).val(response.data.id).attr('data-src', response.data.src);
$('#dialog-box-' + t).modal('hide');
});
uploader.on('uploadProgress', function (file) {
self.setDemoBoxLoading($this);
});
self.bindDelImageBtn('a.btn-del-image');
return uploader;
});
},
// 送出路徑:先做各區塊的必填驗證,全數通過才送出
bindPreviewBtn: function () {
var self = this;
$('#edit-btn, #preview-btn').click(function () {
try {
self.verifyBaseInfo();
self.verifyEleInfo();
self.verifyConclusionInfo();
$('#timeline-form').submit();
} catch (e) {
return HHJsLib.warn(e);
}
});
},
verifyBaseInfo: function () {
HHJsLib.isEmptyByDom('#image-path', '時間軸大圖');
HHJsLib.isEmptyByDom('#cover', '時間軸封面');
HHJsLib.isEmptyByDom('#name', '標題');
HHJsLib.isEmptyByDom('#description', '描述');
},
verifyEleInfo: function () {
this.verifyHeaderEleInfo();
this.verifyTextEleInfo();
this.verifyImageEleInfo();
this.verifyVideoEleInfo();
this.verifyAudioEleInfo();
this.verifyQuestionEleInfo();
this.verifyKnowEleInfo();
},
verifyQuestionEleInfo: function () {
$('div.item-question-box').each(function () {
HHJsLib.isEmptyByDom('#ele-question-content-' + $(this).attr('data-id'), '問題內容');
HHJsLib.isEmptyByDom('#ele-question-extend-' + $(this).attr('data-id'), '問題答案解釋');
$('#answer-box-' + $(this).attr('data-id')).find('textarea').each(function () {
HHJsLib.isEmpty($(this).val(), '問題答案');
});
});
},
verifyConclusionInfo: function () {
var length = $('#conclusion-box div.item-con').length;
HHJsLib.isEmpty(length, '總結');
$('#conclusion-box div.item-con').each(function () {
var dataId = $(this).attr('data-id');
HHJsLib.isEmptyByDom('#ele-con-hash-' + dataId, '總結圖片');
HHJsLib.isEmptyByDom('#ele-con-content-' + dataId, '總結詳情');
});
},
setDemoBoxLoading: function ($target) {
$($target.attr('data-box')).removeClass('no-file').addClass('uploaded');
$($target.attr('data-file-box')).html('');
},
setDemoBoxInit: function ($target) {
$($target.attr('data-box')).removeClass('uploaded').addClass('no-file');
$($target.attr('data-file-box')).html('');
}
});
(原文另有 bindUploadEleVideoBtn、bindDelFileBtn、bindAddAnswerBtn、bindNewConBtn、bindDownloadEleAudioBtn、bindSetPreviewVideo 等方法,結構與上面這幾個一致:命名一律以動詞開頭、職責單一、彼此透過 this 互相呼叫,此處不再重複貼上。)
單一入口。init 就是整頁的目錄,想知道有哪些互動,看它一個就夠,不必全文搜尋 .click(。
this 的傳遞靠 self。每個方法開頭幾乎都有 var self = this;,因為在 $(dom).click(function(){...}) 的內部,this 會被 jQuery 改成 DOM 元素,原本的物件就取不到了。這是這種封裝寫法必付的稅。
動態元素要重新綁定。因為用了樣板字串插入新節點,新插入的按鈕沒有任何事件。所以每個「新增」動作之後,都必須接著呼叫對應的 bind 方法。這個模式在事件委派普及之前很常見。
這份程式碼有幾個明顯可以改進的地方,值得當成反面教材來看:
用事件委派取代重複綁定。上面到處都是「新增元素 → 手動重綁事件」,只要改成綁在父容器上,動態插入的元件自動就有事件,movePlusBtnBox 裡那些 bind 呼叫可以全部刪掉:
$(document).on('click', 'a.btn-del-item', function () {
// 不論元素何時被插進 DOM,這裡都會收到
});
用 data-id 取代時間戳當識別碼。new Date().getTime() 在同一毫秒內新增兩筆就會碰撞。真要產生識別碼,用遞增序號或 crypto.randomUUID() 更可靠。
用 template 元素取代字串拼接。把 eleTplMap 那些用 {t} 佔位、再 replace 替換的字串,改寫成 HTML 的 <template>,內容能被瀏覽器解析檢查,也不容易漏掉跳脫。
innerHTML 拼接有 XSS 風險。程式碼中把 response.data.name 直接拼進 alt 屬性,如果那個值來自使用者輸入,就構成了 injection 的入口。改用 .text() 或 document.createTextNode() 設定文字內容。
驗證用 throw 表達「哪裡錯了」。這部分我倒是覺得原作者的處理不錯:把驗證拆成 verifyBaseInfo、verifyEleInfo、verifyConclusionInfo 三層,用例外中斷流程並把錯誤訊息帶出來,比回傳 boolean 再由呼叫端逐一判斷清楚得多。
整體來說,「用一個物件把相關方法聚合、由 init 統一啟動」這個思路在今天的物件導向 JavaScript 裡依然成立,只是語法可以換成 class,事件綁定可以換成委派,樣板可以換成 <template>。觀念不變,工具變新而已。