JavaScript 專案一大之後,畫面操控的程式就會散落在各處:這裡綁一個 click、那裡初始化一個上傳元件。本文介紹一種沿用 Java 世界「註冊 + 自動啟動」思維的組織方式,把大量的事件綁定收攏到一個入口,讓整體結構一目了然。
與其讓各模組自己在載入時掛事件,不如建立一個中心物件,在 init() 裡依序呼叫所有綁定方法。這麼做的好處是:想知道頁面有哪些互動,只需看 init 一個地方。
const App = {
init() {
this.bindPreviewBtn();
this.bindUploadImageBtn();
this.bindUploadAudioBtn('a.audio-upload-btn');
this.bindUploadVideoBtn('a.video-upload-btn');
this.bindDownloadAudioBtn();
this.bindNewBlockBtn();
this.bindDelBlockBtn('a.btn-del-block');
this.bindDelItemBtn('a.btn-del-item');
this.bindPlusBtn('a.btn-plus');
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.verifyAll(); // 啟動時同步一次狀態
}
};
document.addEventListener('DOMContentLoaded', () => App.init());
這個結構模仿的就是類別的建構子:物件一「實例化」,初始化流程就自動跑完,呼叫端不必記得先呼叫哪個函式。
每個 bindXxx 方法只做一件事,並接受一個選擇器參數,方便重複使用:
bindDelImageBtn(selector) {
this.bindDelFileBtn(selector, '真的要刪除這張圖片嗎?');
},
bindDelAudioBtn(selector) {
this.bindDelFileBtn(selector, '真的要刪除這段音頻嗎?');
},
bindDelFileBtn(selector, message) {
document.querySelectorAll(selector).forEach(target => {
target.addEventListener('click', () => {
if (!confirm(message)) return;
this.removeField(target);
});
});
},
removeField(target) {
document.querySelector(target.dataset.box).innerHTML = '';
document.querySelector(target.dataset.field)
.setAttribute('data-id', '');
}
用 dataset 把「要清空哪個容器」「要重置哪個欄位」寫在 HTML 上,就能避免為每個按鈕寫一份幾乎一樣的程式。
這類畫面通常可以「新增一筆」,而新產生的 DOM 不會自動繼承既有的事件。解法有兩條路:
路子一:新增後立刻補綁。範例中的做法,在插入 HTML 之後馬上呼叫對應的 bind 方法。
addItem(heading, type) {
const id = Date.now();
const html = this.buildItemTemplate(type, id, heading);
document.querySelector(`#block-${heading} .items`).insertAdjacentHTML('beforeend', html);
this.bindDelItemBtn(`#item-${id} a.btn-del-item`); // 立刻補綁
this.reorderPlusButton(heading);
}
路子二:事件委派(更推薦)。把監聽掛在永遠存在的父容器上,利用事件冒泡判斷目標:
document.getElementById('main').addEventListener('click', e => {
const delBtn = e.target.closest('a.btn-del-item');
if (!delBtn) return;
this.removeItem(delBtn.dataset.id);
});
委派方式不必記得補綁,也不會因為新增/刪除而累積多餘的監聽器,是動態 DOM 的首選。
範例裡把 HTML 片段事先準備成 eleTplMap,再用 replace(/{t}/g, ...) 填入變數。這個思路可以整理得更清楚:
buildItemTemplate(type, id, heading) {
const sortNum = this.getNextSortNum(heading);
return `
<div id="item-${id}" data-heading="${heading}" class="item-${type}">
<span class="sort">${sortNum}</span>
<button class="btn-del-item" data-id="${id}">刪除</button>
</div>`;
}
用模板字面值取代 {t} 佔位符,可讀性更好,也不容易漏掉某個 replace。若插入的內容來自使用者輸入,記得先做 HTML 轉義以防 XSS。
把校驗拆成「基礎資料 / 各類元素 / 結論」三層,每層再往下分項,錯誤訊息就能精準指出哪裡沒填:
verifyEleInfo() {
this.verifyBySelector('div.item-heading-box', 'textarea', '頭條內容');
this.verifyBySelector('div.item-text-box', 'textarea', '文本內容');
this.verifyBySelector('div.item-image-box', 'input', '圖片地址');
this.verifyBySelector('div.item-video-box', 'input', '視頻地址');
this.verifyBySelector('div.item-audio-box', 'input', '音頻地址');
}
verifyBySelector(container, field, label) {
document.querySelectorAll(container).forEach(box => {
const input = box.querySelector(field);
if (!input.value.trim()) throw new Error(`${label}不可為空`);
});
}
用統一的 verifyBySelector 收斂五個幾乎相同的函式,是這份程式裡最值得學的重構。
坦白說,中心化的 init 有它的弱點:它假設頁面結構固定。同一份程式套到沒有上傳按鈕的頁面上,就會在 querySelector 拿到 null 時出錯。因此每個 bind 方法都應該先檢查元素是否存在,或改用事件委派讓「找不到就什麼都不做」成為自然結果。
另外,隨著方法數量成長,這個物件最終會變成一隻巨大的 God Object。真要長期維護,較好的方向是依領域拆成獨立模組(上傳模組、排序模組、驗證模組),各自匯出一個 init,再由最上層逐一啟動——這其實就是同一個模式,只是把「一個大物件」換成「多個小物件」。理解這一點,你就掌握了從腳本過渡到模組化架構的關鍵一步。