0

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?

3
  • I can't see by your code why you need to have this test class subscribed to the oncanplay event, but you could just have the function associated with vid.oncanplay use your test class object and call a function from it which does what you want when oncanplay is fired. Commented Feb 17, 2020 at 14:02
  • @RyanWilson The test class is just a simplified example. I have a big number of classes, and they all have to be aware of the different events. Commented Feb 17, 2020 at 14:06
  • @yakpsideman I would just have each class perform it's desired work inside the function associated with the oncanplay event callback. Commented Feb 17, 2020 at 14:16

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Only the LAST event handler assigned gets run, because you assigned them as properties. Try use addEventListener() instead.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.