「介面與資料分離」不只是口號,必須落實在程式碼結構:UI 程式碼零依賴資料存取邏輯,資料層零耦合 UI 元件。本文以 jQuery + Callback/Event 模式示範純前端分離架構,可直接套用至 Vue/React/Angular 的 Service/Store 概念。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>UI-Data Separation Demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(function () {
// ========== 資料層 ==========
var Countries = function () {}
Countries.prototype = {
_items: [],
_getData: function (success) {
var items = [
{ id: 0, name: '中國' },
{ id: 1, name: '日本' },
{ id: 2, name: '美國' }
];
$.extend(this._items, items);
success(items);
},
// 事件訂閱機制
on_selected: $.Callbacks(),
on_inserted: $.Callbacks(),
// 對外方法
select: function () {
var self = this;
this._getData(function (items) {
self.on_selected.fire({ sender: self, items: items });
});
},
insert: function (item) {
this._items.push(item);
this.on_inserted.fire({ sender: self, item: item });
}
};
// ========== UI 層 (僅此區塊可修改) ==========
var countries = new Countries();
countries.on_selected.add(function (args) {
$(args.items).each(function () {
$('#countries').append($('<option>').attr('value', this.id).text(this.name));
});
});
countries.on_inserted.add(function (args) {
$('#countries').append($('<option selected="selected">').attr('value', args.item.id).text(args.item.name));
});
var id = 10;
$('#btnAdd').click(function () {
countries.insert({ id: ++id, name: $('#countryName').val() });
});
countries.select();
});
</script>
</head>
<body>
<select id="countries"></select>
<div>
<input id="countryName" /><button id="btnAdd">新增</button>
</div>
</body>
</html>
| 層級 | 程式碼區塊 | 職責 | 依賴 |
|---|---|---|---|
| Model | Countries 類別 | 資料快取、模擬 AJAX、事件發送 | 無 (純 JS) |
| View | countries.on_selected.add... 區塊 | DOM 操作、事件綁定、使用者互動 | jQuery、Model 事件 |
interface Country { id: number; name: string } 強化型別安全。此模式為現代前端框架「資料驅動視圖」的基石,理解並實踐它,架構才不會隨專案增長而崩壞。