javascriptdom-eventsevent-listener

Multiple event listener on the same object not working


Is it possible to have two listener listening to the same event? I have an event listener listening for the oncanplay video event, and in some other class, in this example the test class, I have to listen to the same event.

<!DOCTYPE html> 
<html> 
<body> 

<button onclick="playVid()" type="button">Play Video</button>
<button onclick="pauseVid()" type="button">Pause Video</button><br> 

<video id="myVideo" width="320" height="176" autoplay>
  <source src="mov_bbb.mp4" type="video/mp4">
  <source src="mov_bbb.ogg" type="video/ogg">
  Your browser does not support HTML5 video.
</video>

<script> 

const test = () => {

  vid.oncanplay = function() {
  console.log("CAN PLAY 2!")
};
}

var vid = document.getElementById("myVideo"); 
test();

  vid.oncanplay = function() {
  console.log("CAN PLAY 1!")
};

function playVid() { 
  vid.play(); 
} 

function pauseVid() { 
  vid.pause(); 
} 
</script> 

</body> 
</html>

In this case only CAN PLAY 1 will be fired. If I remove the CAN PLAY 1 listener, CAN PLAY 2 will than be fired. Can I have both event be fired?


Solution

  • oncanplay is a property of the object, and it can be assigned to multiple times, but only the last assignment means anything, as you overwrite the value.

    It's like...

    a=2;
    a=1;
    console.log(a);
    //as you'd expect, it would output the value of 1
    

    As has been suggested, you can put multiple event listeners on the object by using

    vid.addEventListener("canplay",
                         function() {
                            console.log("CAN PLAY 1!");
                          });
    

    ...because addEventListener doesn't overwrite previously created event listeners.

    Also, as a side note, keep in mind, doing this with an anonymous function will make it difficult to remove the event listener later; as, being anonymous, there is no named reference to allow you to access it during a removeEventListener request.