I have an object called Gallery with several properties and methods. One of them, setCurrentPicture, removes all existing DOM photo and video elements from the gallery container before showing a new photo / video. In addition, my gallery stops playing the video (set it to pause) when the user clicks on it. This is the togglePlayVideo method inside the gallery prototype. First, I remove the elements from the DOM, and then show the new content. If this video, I add eventListener for documentation, use the binding method.
So, in setCurrentPicture I want to remove the EventListener for the video elements. Is it possible to associate this context with a document inside the Array.prototype.forEach method when removing eventListener? If I saved the necessary context to a new variable, then I succeeded. But then I try to bind, my IDE says "Potentially invalid use of this."
Code snippet:
Gallery.prototype = { setCurrentPicture: function(currentPhoto) { var self = this; Array.prototype.forEach.call(container.children, function(item) { if (item.tagName === 'VIDEO') { document.removeEventListener('click', self.togglePlayVideo); } if (item.tagName === 'VIDEO' || item.tagName === 'IMG') { container.removeChild(item); } }); if (pictures[currentPhoto] instanceof Video) { var video = document.createElement('video'); .... document.addEventListener('click', self.togglePlayVideo); } }, }, togglePlayVideo: function(e) { if (e.target.tagName === 'VIDEO') { return e.target.paused ? e.target.play() : e.target.pause(); } } }
In case of adding document.addEventListener('click', self.togglePlayVideo); I can use bind instead of self: document.addEventListener('click', this.togglePlayVideo.bind(this) .
Is it possible to use bind in removeEventListener? document.removeEventListener ('click', this.togglePlayVideo.bind (this);
source share