JavaScript 中,同名函數後定義的會覆蓋先定義的。這個「缺陷」反過來用,恰好能實現設計模式裡的模板方法:把公共流程寫一次,把差異點留給各頁面重寫。
項目裡有大量展示數據庫記錄的列表頁,操作步驟幾乎一致:初始化表格、讀取列表、查詢、新增、編輯、刪除、關閉彈窗並刷新。差別只在後台接口地址、列配置和查詢條件。為每個頁面複製一份完整代碼顯然不合理。
把共性邏輯集中到一個構造函數中,關鍵結構如下:
function ListCommon2() {
var urlAdd;
var urlAjax;
var tableid;
var titleText="";
var winid = "#win";
var columns;
var toolbars;
var queryParams;
var colkey;
var toolbarsType
// 初始化配置:傳入接口地址、表格 id、標題、彈窗選擇器、列定義等
this.initList = function (aurlAdd, aurlAjax, atableid, atitleText, awinid, acolumns, atoolbarsType) {
urlAdd = aurlAdd;
urlAjax = aurlAjax;
if (atableid) { tableid = atableid; }
if (atitleText) { titleText = atitleText; }
if (atitleText) { winid = awinid; }
columns = acolumns;
toolbarsType = atoolbarsType;
};
// 初始化數據:組裝工具列、綁定 datagrid、掛事件
this.initData = function () {
if (!toolbarsType) {
toolbars = [{ text: '添加', iconCls: 'icon-add', handler: Add }, '-', { text: '編輯', iconCls: 'icon-edit', handler: this.Edit }
, '-', { text: '刪除', iconCls: 'icon-cancel', handler: this.delMsg }
];
} else {
toolbars = toolbarsType;
}
queryParams = this.GetqueryParams();
$(tableid).datagrid({
url: urlAjax + '?OperationType=list',
columns: columns,
toolbar: toolbars,
idField: colkey,
pagination: true,
pageSize: 20,
sortName: colkey,
sortOrder: 'desc',
rownumbers: true, fitColumns: true,
striped: true,
method: "post",
queryParams: this.GetqueryParams(),
showFooter: true
, pageList: [10, 20, 30, 40, 50]
});
$("#add").click(function (e) { Add(); });
$("#edit").bind('click', { obj: this }, function (event) { event.data.obj.Edit(); });
$("#del").bind('click', { obj: this }, function (event) { event.data.obj.delMsg(); });
$("#btnQuery").bind('click', { obj: this }, function (event) {
var queryParamsnew = event.data.obj.GetqueryParams();
$(tableid).datagrid('load', queryParamsnew);
});
}
// 查詢參數組裝
this.GetqueryParams = function () {
var NameList = this.Getcolsinfo();
var otherQueryParams = this.GetOtherQueryParams();
if (!otherQueryParams) {
return { colkey: colkey, colsinfo: NameList };
} else {
return otherQueryParams;
}
}
// 差異點:默認返回 null,交由具體頁面重寫
this.GetOtherQueryParams = function () { return null; }
this.Getcolsinfo = function () {
var fieldNameList = [];
if (columns.length > 0) {
for (var i = 0; i < columns[0].length; i++) {
fieldNameList.push(columns[0][i].field);
}
} else { alert("未綁定數據"); }
colkey = fieldNameList[fieldNameList.length-1];
return fieldNameList.join(",");
}
// 新增:以 iframe 形式加載表單頁
function Add() {
var _content = '<iframe id="FRMdetail" frameborder="0" src=' + urlAdd + ' style="width:100%;height:100%;" ></iframe>';
$(winid).dialog({ width: 600, height: 400, modal: true, content: _content, title: "增加" + titleText, draggable: true, resizable: true, shadow: true, minimizable: false });
}
// 編輯:支持傳 id 或從表格選中行取 id
this.Edit = function (editId) {
var id; var obj = typeof (editId);
if (!editId || obj == "object") {
var items = $(tableid).datagrid('getSelections');
var length = items.length;
if (length == 0) { $.messager.alert('提示', '請選擇一條記錄然後編輯'); return; }
else if (length > 1) { $.messager.alert('提示', '由於一次只能編輯一條記錄,所以只能修改第一條記錄'); return; }
id = GetId(items[0]);
} else { id = editId; }
var _content = '<iframe id="FRMdetail" frameborder="0" src=' + urlAdd + '?Id=' + id + ' style="width:100%;height:100%;" ></iframe>';
$(winid).dialog({ width: 600, height: 400, modal: true, content: _content, title: "修改" + titleText, draggable: true, resizable: true, shadow: true, minimizable: false });
}
this.windowclose = function () { $(winid).window('close'); }
this.SaveOkCallback = function () {
this.windowclose();
$(tableid).datagrid('reload');
$(tableid).datagrid('unselectAll');
}
// 刪除:支持單條與批量,帶確認提示
this.delMsg = function (delId) {
var length = 1; var id; var items; var obj = typeof (delId);
if (!delId || obj == "object") {
items = $(tableid).datagrid('getSelections');
length = items.length;
if (length == 0) { $.messager.alert('提示', '請至少選擇一條記錄然後刪除'); return; }
} else { id = delId; }
var text = '你確認刪除' + length + '條記錄嗎?';
if (length == 1) { text = '你確認刪除該條記錄嗎?'; }
$.messager.confirm('提示', text, function (r) {
if (r) {
if (!delId) {
var idList = [];
$.each(items, function (key, value) {
var id = GetId(value);
idList.push(id);
});
id = idList.join(",");
}
del(id)
}
});
}
function del(id) {
$.ajax({ type: "post",
url: urlAjax + "?OperationType=del&id=" + id,
success: function (msg) {
var obj = jQuery.parseJSON(msg);
if (obj.IsSuccess == true) { $.messager.alert('提示', obj.Msg); selectcallback(); }
else { $.messager.alert('提示', obj.Msg); }
}
});
}
function selectcallback() { SaveOkCallback(); }
}
細看會發現,這段代碼幾乎覆蓋了增刪改查全流程,唯一需要各頁面自己定義的就是 this.GetOtherQueryParams:
$(document).ready(function () {
obj = new ListCommon2();
obj.initList(urlAdd, urlAjax, tableid, titleText, winid, columns, '#tb');
obj.GetOtherQueryParams = function () {
var colsinfo = obj.Getcolsinfo();
return { colsinfo: colsinfo, SWV_Performance_fk: $('#SWV_Performance_fk').combobox('getValue'), S_NAME: $("#S_NAME").val(), SQ_NAME: $("#SQ_NAME").val() };
};
obj.initData();
})
也可以完全不去定義方法,只在具體頁面補上被調用但未實現的函數,例如 GetId:
<script type="text/javascript">
function GetId(item) {
return item.SWV_ID
}
</script>
還有一種做法是傳入一個回調函數。三種方式都能達到目的,但就結構清晰度而言,模板方法(重寫差異方法)最為直觀。