Native package javascript event listener function

        javascript has a lot of functions and methods are already good package, the user only needs to get the direct use, greatly simplifying the code, the user experience more convenient, but if you learned the native javascript knows that these methods can be encapsulated themselves out, wrapper function able to understand the underlying implementation js, and have a better understanding of javascript, today I try to encapsulate a function of time listening ------ addEventListener and rmoveEventListener.

         First, some achieve addEventListener and rmoveListener of the Code

<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>

This page will appear when the upper and lower boxes, we give him listening binding function

foo1 function () { 
  the console.log (. 1) 
 } 
  function foo2 () { 
  the console.log (2) 
 } 
 box1.addEventListener ( "the Click", foo1) 
 box1.addEventListener ( "the Click", foo2) 
 // bind to box1 click on the two events, just click on the box box1 two events will trigger function, output 2 1 
 box1.removeEventListener ( "the click", foo1) 
 // add the box1 foo1 binding function canceled, only this time click on the box output 2

This is the function that we can monitor directly, the following two package my name on the prototype is not the same, but the same performance function, after reading this, I believe we can have some understanding of the addEventListener and 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))
        }
  }
 }

  Try to own the underlying function package can have a more profound understanding of the native javascript, after using the framework will be very easy to use.

Guess you like

Origin www.cnblogs.com/388ximengpy/p/12111264.html