Removing multiple resets from createResetHandler

Starting from the inside of the code, the managePlayer module has another method added to it to remove (using destroy) a player.

 function removePlayer(player) {
   player.destroy();
 }
...
 return {
   adder: playerAdder,
   remove: removePlayer
 };

We can now use that removePlayer code from the resetVideoHandler function.

      video.addEventListener("click", function resetVideoHandler() {
        managePlayer.remove(player);
      });

The next stage for that code is to replace the resetVideoHandler code with managePlayer.removeHandler instead, but before doing that we need to use an evt variable to gain the player.

We can add evt to the function:

      video.addEventListener("click", function resetVideoHandler(evt) {
        ...
      });

and use the evt target to gain the wrapper. The evt.target refers to the exit button so we can get the highest-level parent for each video, which is the container element.

        const el = evt.target;
        const container = el.closest(".container");
        const wrapper = container.querySelector(".wrap");
        managePlayer.remove(wrapper.player);

That resetVideoHandler function can now be moved out to the managePlayer code as a function called removePlayerHandler

  function createResetHandler(player) {
    const resetVideo = document.querySelectorAll(".exit");
    resetVideo.forEach(function resetVideoHandler(video) {
      video.addEventListener("click", managePlayer.removeHandler)
    });
  }

And from there, the player parameter isn’t needed anymore, so a callback variable can be used there instead to refer to managePlayer.removeHandler

  // function createResetHandler(player) {
  function createResetHandler(callback) {
    const resetVideo = document.querySelectorAll(".exit");
    resetVideo.forEach(function resetVideoHandler(video) {
      video.addEventListener("click", callback)
    });
  }
...
    // createResetHandler(player);
    createResetHandler(managePlayer.removeHandler);

And lastly, that createResetHandler shouldn’t be run every time a player is added, but only once when the page is loaded. Also the createResetHandler function doesn’t belong in the videoPlayer code because it deals with the exit buttons, so moving createResetHandler to the manageUI code needs to be done, along with adding a public method to the end of the manageUI code so that it can be accessed. This is also a good time to rename createResetHandler to addExitHandlers too.
so moving that to the start of the onYouTubeIframeAPIReady function is a good solution to that.

Some of the work that needs to be done is described in the text so you may need some help with that, but all of the information is there to successfully achieve a good and working solution.

1 Like