I have an object named Gallery with several properties and methods. One of them, setCurrentPicture, removes all existing photos and videos DOM elements from gallery container before showing new photo/video. Besides my gallery stops playing video (set this to pause mode) when the user clicks on it. This is togglePlayVideo method inside the Gallery prototype. First I remove elements from DOM and then showing new content. If this is video, I add eventListener to document, use bind method.
So, in the setCurrentPicture I want to remove EventListener on video elements. Is it possible to bind this context to document inside Array.prototype.forEach method when deleting eventListener? If I saved the necessary context into new variable then I got succeed. But then I'm trying bind, my IDE is saying 'Potentially invalid usage 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 addition document.addEventListener('click', self.togglePlayVideo);
I can use bind instead of self: document.addEventListener('click', this.togglePlayVideo.bind(this)
.
Can I use bind in removeEventListener? document.removeEventListener('click', this.togglePlayVideo.bind(this);