Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use vue.js method in EventListener click in other method

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);

                
            }
        }
    });
}
like image 676
Sirence Avatar asked Jan 02 '23 06:01

Sirence


1 Answers

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.

like image 79
Thoomas Avatar answered Jan 05 '23 14:01

Thoomas