js设计模式之模版方法模式的应用

本文介绍模版方法模式的概念并提供了一个JavaScript示例。该示例通过创建一个提示框模版,允许用户通过继承来定制不同的提示框样式,如右对齐提示框和带标题的提示框。

模版方法模式:定义一组操作算法框架,而将一些实现步骤延迟到子类中,使得子类可以不改变父类的算法结构的同时可重新定义算法中某些实现步骤。

1、源码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
	<meta charset="utf-8">
	<style>
		div {
			margin-top: 5px;
			border:solid 1px blue;
			padding: 5px;
		}
	</style>
</head>
<body>

 <script type="text/javascript">
window.onload = function(){
 	/* 提示框模版 */
 	var Alert = function(data){
 		if(!data)return;
 		this.content = data.content || "默认提示框内容";;
 		this.panel = document.createElement("div");
 		this.contentNode = document.createElement("p");
 		this.confirmBtn = document.createElement("button");
 		this.closeBtn = document.createElement("b");
 		this.panel.className = "alert";
 		this.closeBtn.className = "a-close";
 		this.confirmBtn.className = "a-confirm";
 		this.confirmBtn.innerHTML = data.confirmBtn || "确认";
 		this.contentNode.innerHTML = this.content
 		this.success = data.success || function(){};
 		this.fail = data.fail || function(){};
 	}
 	Alert.prototype = {
 		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;
 			this.closeBtn.onclick = function(){
 				me.fail();
 				me.hide();
 			}
 			this.confirmBtn.onclick = function(){
 				me.success();
 				me.hide();
 			}
 		},
 		hide : function(){
 			this.panel.style.display = "none";
 		},
 		show : function(){
 			this.panel.style.display = "block";
 		}
 	}
 	//1、实例化一个默认的提示框
 	new Alert({}).init();//


 	//2、实例化一个定制的提示框
 	var RightAlert = function(data){
 		Alert.call(this,data);
 		this.confirmBtn.className = this.confirmBtn.className+" right";
 	}
 	RightAlert.prototype = new Alert();

 	var data = {
 		content : "我是定制的Alert",
 		confirmBtn : "Ok",
 		title :"我是title"
 	}
 	new RightAlert(data).init();

 	//3、定制一个带标题的提示框
 	var TitleAlert = function(data){
 		Alert.call(this,data);
 		this.title = data.title;
 		this.titleNode = document.createElement("h3");
 		this.titleNode.innerHTML = this.title;
 	}
 	TitleAlert.prototype = new Alert();
 	TitleAlert.prototype.init = function(){
 		this.panel.insertBefore(this.titleNode,this.panel.firstChild);
		Alert.prototype.init.call(this);
 	}
 	new TitleAlert(data).init();
		
 };


 </script>

</body>

</html>

2、效果

004320_aF13_2391658.png

初始化展示提示框,点击按钮可以隐藏这个提示框。

转载于:https://my.oschina.net/u/2391658/blog/979125

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值