JavaScript委托

2012-03-24  金城  2366

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type"content="text/html;charset=utf-8"/>
  <title>无标题文档</title>
  <script type="text/javascript">
  var delegate1=function(){
  //委托的方法列表
  var Fuctions=[];
  //添加一个委拖
  this.AddF=function(f){
  if(typeof(f)==="function"){
    Fuctions.push(f);
  }else{
    throw new Error("要传function !!!");
  }
  };
  //去除委拖
  this.removeDelegate=function(f){
  if(typeof(f)==="function"){
    var length=Fuctions.length;
    for(var i=0;i <length;i++){
    if(Fuctions[i]== f){
      Fuctions.splice(i,1);
    }
    }
  }else{
    throw new Error("委托只能接受方法");
  }
  };
  //调用委托
  this.Run=function(){
  for(var item in Fuctions){
    Fuctions[item]();
  }
  }
}
function clicks(){
  var oBtn2=document.getElementById("ipt2");
  oBtn2.onclick=function(){
  alert("我被触发");
  };
}
window.onload=function(){
  var oBtn1=document.getElementById("ipt1");
  oBtn1.onclick=function(){
  var del=new delegate1();
  del.AddF(clicks);
  del.Run();
  }
}
</script>
</head>
<body>
 <input id="ipt1"type="button"value="设置委拖"/><br/>
 <input id="ipt2"type="button"value="执行委拖"/>
</body>
</html>