本文摘自 《JavaScript 設(shè)計模式》張容銘 著 版權(quán)歸原作者所有
模板方法模式
模板的原型方法
var Alert = function(){};
Alert.prototype = {
// 創(chuàng)建方法
init:function(){
// 生成提示框
this.panel.appendChild(this.closeBtn);
this.panel.appendChild(this.contentNode);
this.panel.appendChild(this.confirmBtn);
// 插入頁面中
document.body.appendChild(this.panel);
// 綁定事件
this.bindEvent();
// 顯示提示框
this.show();
},
bindEvent : function(){
var me = this;
// 關(guān)閉按鈕點擊事件
this.closeBtn.onclick = function(){
// 執(zhí)行關(guān)閉取消方法
me.fail();
// 隱藏彈層
me.hide();
},
},
// 隱藏彈層方法
hide : function(){
this.panel.style.display = 'none';
},
// 顯示彈層方法
show : function(){
this.panel.style.display = 'block';
}
}
根據(jù)模板創(chuàng)建類
// 右側(cè)按鈕提示框
var RAlert = function(data){
// 繼承基本提示框構(gòu)造函數(shù)
Alert.call(this,data);
// 為確認按鈕添加right類設(shè)置位置居右
this.confirmBtn.className = this.confirmBtn.className + 'right';
}
// 繼承基本提示框方法
RAlert.prototype = new Alert();
// 標題提示框
var TitleAlert = function(data){
// 繼承基本提示框構(gòu)造函數(shù)
Alert.call(this,data);
// 設(shè)置標題內(nèi)容
this.title = data.title;
// 創(chuàng)建標題組件
this.titleNode = document.creareElement('h3');
// 標題組件中寫入標題內(nèi)容
this.titleNode.innerHTML = this.title;
}
// 繼承基本提示框方法
TitileAlert.prototype = new Alert();
// 對基本提示框創(chuàng)建方法拓展
TitleAlert.prototype.init = function(){
// 插入標題
this.panel.inserBefore(this.titileNode,this.panel.firstChild);
// 繼承基本提示框init方法
Alert.prototype.init.call(this);
}
繼承類也可作為模板類
// 帶有取消按鈕的彈出框
var CancelAlert = function(data){
// 繼承標題提示框構(gòu)造函數(shù)
TitleAlert.call(this,data);
// 取消按鈕文案
this.canel = data.cancel;
// 創(chuàng)建取消按鈕
this.cancelBrn = document.createElement('span');
// 為取消按鈕添加類
this.cancelBtn.className = 'cancel';
// 設(shè)置取消按鈕內(nèi)容
this.cancelBtn.innerHTML = this.cancel || '取消';
}
// 繼承標題提示框原型方法
CancelAlert.prototype= newAlert();
CancelAlert.prototype.init = function(){
var me = this;
// 標題提示框綁定事件方法繼承
TitleAlert.prototype.bindEvent.call(me);
// 取消按鈕綁定事件
this.cancelBtn.onclick = function(){
// 執(zhí)行取消回調(diào)函數(shù)
me.fail();
// 隱藏彈層
me.hide();
}
}
創(chuàng)建一個提示框
new CancelAlert({
title:'提示標題',
content:'提示內(nèi)容',
success:function(){
console.log('ok');
},
fail:function(){
console.log('cancel')
}
}).init();