原生javascript封装事件监听函数

        javascript中有很多函数和方法是已经封装好了的,用户只需要拿到直接使用,大大简化 了代码,用户体验更方便,但是如果学过原生javascript的都知道,这些方法都可以自己封装出来,封装函数能够了解底层js的实现,对javascript有更深的认识,今天我自己尝试封装了时间监听函数 ------addEventListener和rmoveEventListener.

         首先介绍一下addEventListener和rmoveListener的实现,上代码

<style>
 .box1{
  width:100px;
  height:100px;
  background-color: blueviolet;
  
 }
 .box2{
  width:100px;
  height: 100px;
  background-color: chocolate;
 }
 </style>
</head>
<body>
 <div class="box1"></div>
 <div class="box2"></div>
</body>

这时候页面会出现上下两个盒子,我们给他绑定监听函数

 function foo1(){
  console.log(1)
 }
  function foo2(){
  console.log(2)
 }
 box1.addEventListener("click",foo1)
 box1.addEventListener("click",foo2)
 //给box1绑定了两个点击事件,只要点击盒子box1就会触发两个事件函数,输出1 2 
 box1.removeEventListener("click",foo1)
 //把box1其中添加foo1的绑定函数取消,这时候点击盒子就只输出2 

这是我们能直接用的监听函数,下面我在原型上封装两名字不一样,但是功能一样的函数,看完这个,相信大家就能对addEventListener和rmoveListener有一定的了解了

HTMLElement.prototype.myaddEventListener =function(type,handleFunction){
  this.eventObject = this.eventObject|| {}
  type = type.toLowerCase()
  this.eventObject[type] = this.eventObject[type] || []
  if(this.eventObject[type].includes(handleFunction))  return  //有相同名的函数就不执行
  this.eventObject[type].push(handleFunction)
  this["on"+type] = e =>{
   this.eventObject[type].forEach(fn => (fn(e)));
  }
 }
 HTMLElement.prototype.myRemoveEventListener = function(type,handleFunction){
  if(this.eventObject[type].includes(handleFunction)){
   this.eventObject[type] = this.eventObject[type].filter(item =>item!=handleFunction)
   this["on"+type] = e => {
          this.eventObject[type].forEach(fn => fn(e))
        }
  }
 }

  试着自己封装底层函数能够对原生javascript有更深刻的认识,以后使用框架也会很容易上手。

猜你喜欢

转载自www.cnblogs.com/388ximengpy/p/12111264.html
今日推荐