您的位置:首页 > Web前端 > JavaScript

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

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

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、效果



初始化展示提示框,点击按钮可以隐藏这个提示框。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息