10

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

                
            }
        }
    });
}

2
  • inside the 'function(){ ... }' containing 'this.openLightbox(src)' 'this' is not what you think it is. add 'var self = this' before the function, and use 'self.openLightbox(src)' Commented Jun 12, 2018 at 13:11
  • Oh wow, you are completely correct! Commented Jun 12, 2018 at 13:15

1 Answer 1

16

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.