I have a vue.js script that generates an element 'lens' in a method. Now, I would like to add an EventListener that calls another method when the lens element is clicked.
The issue:
I have tried two different ways to add the listener.
1: lens.addEventListener("click", this.openLightbox(src));
Works but is executed on pageload, not on click
2: lens.addEventListener("click", function() { this.openLightbox(src) }, false);
Is executed on click and not on payload, but throws error: Uncaught TypeError: this.openLightbox is not a function
The question:
How can I call the lightbox method in my zoom method? I does work if I copy the code from the lightbox mehtod into the zoom method itself as a function, however since the lightbox method is called by other elements as well that would lead to duplicate code.
Here is the full code:
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");
// works but is executed on pageload, not on click
lens.addEventListener("click", this.openLightbox(src));
// Is executed on click and not on payload, but throws error: Uncaught TypeError: this.openLightbox is not a function
lens.addEventListener("click", function() { this.openLightbox(src) }, false);
}
}
});
}
You have to attach this
to the anonymous function like this :
lens.addEventListener("click", function() { this.openLightbox(src) }.bind(this), false);
Or define an alias before the statement, like this :
var self = this;
lens.addEventListener("click", function() { self.openLightbox(src) }, false);
Otherwise, this
will not reference the parent context that you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With