Build Your Own JavaScript DOM Library
About Lesson

 420 total views,  4 views today

Let’s add the event listener by creating an “on” method. We use the addEventListener method to attach and event listener to the element. The addEventlisterner takes in the event name, callback function as the parameter.

The last parameter “false” is the options or the useCapture (true/false). More about that later.

 // Attach event listener
  Q.fn.on = function (name, handler) {
    return this.each(function (e) {
      e.addEventListener(name, handler, false);
    })
  }

Let’s write a “off” method to remove the event listener. To remove an event listener we use the element’s removeEventListener. We need the name of the event and the handler function for this.

  // Detach/remove event listener
  Q.fn.off = function (name, handler) {
    return this.each(function (e) {
      e.removeEventListener(name, handler);
    })
  }

Example => Step 16 -> Add remove event listeners

Let’s test our code.


Q(() => {
  test("add event listeners", function() {
    let $btnAdd = Q("#btnAdd");
    
    function fn(e) {
      alert("After 1 second, this event will be switched off");
      
      setTimeout(()=> {
        $btnAdd.off("click", fn);  
      }, 1000);
    }
    $btnAdd.on("click", fn);
    
    function fn2(e) {
      alert(e.target.innerText);
    }
    Q("ul>li").on("click", fn2);
  });
});
0% Complete