16.第四篇:行为型设计模式

本文摘自 《JavaScript 设计模式》张容铭 著 版权归原作者所有

模板方法模式

模板的原型方法

var Alert = 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();
    },
  },
  // 隐藏弹层方法
  hide : function(){
        this.panel.style.display = 'none';
  },
  // 显示弹层方法
  show : function(){
    this.panel.style.display = 'block';
  }
}

根据模板创建类

// 右侧按钮提示框
var RAlert = function(data){
  // 继承基本提示框构造函数
  Alert.call(this,data);
  // 为确认按钮添加right类设置位置居右
  this.confirmBtn.className = this.confirmBtn.className + 'right';  
}
// 继承基本提示框方法
RAlert.prototype = new Alert();

// 标题提示框
var TitleAlert = function(data){
  // 继承基本提示框构造函数
  Alert.call(this,data);
  // 设置标题内容
  this.title = data.title;
  // 创建标题组件
  this.titleNode = document.creareElement('h3');
  // 标题组件中写入标题内容
  this.titleNode.innerHTML = this.title;
}
// 继承基本提示框方法
TitileAlert.prototype = new Alert();
// 对基本提示框创建方法拓展
TitleAlert.prototype.init = function(){
  // 插入标题
  this.panel.inserBefore(this.titileNode,this.panel.firstChild);
  // 继承基本提示框init方法
  Alert.prototype.init.call(this); 
}

继承类也可作为模板类

// 带有取消按钮的弹出框
var CancelAlert = function(data){
  // 继承标题提示框构造函数
  TitleAlert.call(this,data);
  // 取消按钮文案
  this.canel = data.cancel;
  // 创建取消按钮
  this.cancelBrn = document.createElement('span');
  // 为取消按钮添加类
  this.cancelBtn.className = 'cancel';
  // 设置取消按钮内容
  this.cancelBtn.innerHTML = this.cancel || '取消';
}
// 继承标题提示框原型方法
CancelAlert.prototype= newAlert();
CancelAlert.prototype.init = function(){
  var me = this;
  // 标题提示框绑定事件方法继承
  TitleAlert.prototype.bindEvent.call(me);
  // 取消按钮绑定事件
  this.cancelBtn.onclick = function(){
    // 执行取消回调函数
    me.fail();
    // 隐藏弹层
    me.hide();
  }
}

创建一个提示框

new CancelAlert({
  title:'提示标题',
  content:'提示内容',
  success:function(){
    console.log('ok');
  },
  fail:function(){
    console.log('cancel')
  }
}).init();

你可能感兴趣的:(16.第四篇:行为型设计模式)