简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM