In my Vue.js script, I have a method that generates an element called 'lens'. Now, I want to include an EventListener that triggers another method when the lens element is clicked.
The problem:
I have attempted two different approaches to add the listener.
1:
lens.addEventListener("click", this.openLightbox(src));
This works, but it runs on pageload instead of on click
2:
lens.addEventListener("click", function() { this.openLightbox(src) }, false);
It executes on click rather than on pageload, but it throws an error:
Uncaught TypeError: this.openLightbox is not a function
The question:
How can I invoke the lightbox method within my zoom method? It does work if I duplicate the code from the lightbox method inside the zoom method as a function, but that would create redundant code since the lightbox method is also called by other elements.
Below is the complete code snippet:
initVue(target: string) : void {
this.vue = new Vue({
el: "#" + target,
store,
delimiters: vueDelimiters,
data: {
},
methods: {
openLightbox(src) {
console.log(src);
},
imageZoom(src) {
lens = document.createElement("DIV");
// This runs on pageload instead of click
lens.addEventListener("click", this.openLightbox(src));
// This throws an error: Uncaught TypeError: this.openLightbox is not a function
lens.addEventListener("click", function() { this.openLightbox(src) }, false);
}
}
});
}