Employ the vue.js method within the click EventListener of another method

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

                
            }
        }
    });
}

Answer №1

Make sure to connect this to the anonymous function in the following way :

lens.addEventListener("click", function() { this.openLightbox(src) }.bind(this), false);

Alternatively, you can create an alias before the code, like this :

var self = this;
lens.addEventListener("click", function() { self.openLightbox(src) }, false);

If you don't do this, this won't refer back to the necessary parent context.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to broaden the map of a variable in SCSS

Currently, I am utilizing a package known as Buefy, which acts as a Vue.js wrapper for the Bulma CSS framework library. Within Buefy's template components, there is an attribute/property called type (e.g., type="is-warning"). According to the document ...

Distinguishing SharePoint React Webpart from Office: A Comparison

My goal is to develop a client-side Webpart in React for SharePoint Online that utilizes OfficeJs to initiate a new email message on the user's Outlook desktop. However, I'm encountering a persistent "Office is not defined" error no matter what ...

React-router-sitemap lacks a definition for 'Require'

According to the official documentation here, this is how the sitemap-builder.js file should be structured: require('babel-register'); const router = require('./router').default; const Sitemap = require('../').default; ( ...

HTML: Determine the Precise Location of a Div Element That is Centered

Imagine I have this image: Is there a way for me to determine the x/y or left/top properties of my canvas if it is centered using the following CSS: #canvas-container { width: 100px; height:100px; margin: 0px auto; } Note ...

How can I initiate an AJAX POST request over HTTPS?

Despite my efforts, I am consistently encountering a 404 error when attempting to make an Ajax POST request. The specific error message reads: "GET 404 (Not Found)." Could this issue be related to the site's use of https? Below is the code snippet t ...

Personalizing buttons on a carousel in React-bootstrap

I am facing an issue with my carousel and buttons placement. The buttons need to be outside of the carousel, but I'm unsure how to connect them effectively. React-Bootstrap's activeIndex option was suggested, but since my carousel is not cyclic l ...

Authentication failed due to Bcrypt.compare() returning invalid credentials

const express = require('express'); const router = express.Router(); const auth = require('../../middleware/auth'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const config = require(&apo ...

Developing an npm library with ReactJs: A step-by-step guide

As a newcomer to React, I am eager to create my own npm library in ReactJS. Taking inspiration from my existing React project, the goal is to transform it into a package (or library) that can be easily integrated into other projects. This means allowing ...

Issues Arise when Attempting to Upload Files to AWS S3 Using Node.js as

Utilizing this AWS S3 NPM Package for managing S3 uploads from my Express server has presented me with a puzzling situation. The uploader fails to trigger the end function. var key = utils.createID(Date.now()); var s3 = require('s3'); var client ...

Browsing through items within arrays to evaluate their values

I am facing an issue with two arrays that consist of objects. The first array contains restaurant objects with attributes such as name and averagePrice, while the second array has price objects (cheap, medium, expensive) with properties like label, lowEnd, ...

"Using Javascript to assign a class based on a date being greater than

I am facing an issue with a script that applies a CSS class to table cells if the date is greater than a certain value. Currently, the script only works for today's date. I need it to work for dates within and outside of this week as well. $('td ...

The animation is not updating quickly enough

I'm working on a navigation bar that sticks to the top of the page. As the user scrolls down, I want the bar to shrink, and when they scroll back up, it should return to its original size. Issue: The problem I'm facing is that when the user quic ...

Tips for effectively handling a prop in an HTML form using Vue.js and avoiding infinite loops with a computed property

I have a Vue.js form for signing up that features numerous similar fields. From my understanding, I should initialize the values as props rather than objects or arrays (since they will be pass-by-value). My approach involves using a computed property with ...

Using Node.js to separate applications on the same URL based on different paths

We currently have a server hosting one domain, where we have placed apps separately using specific URL paths. For instance, the front-end of our app is mapped to the main URL (/). Requests to / will be directed to the front-end app, while adding /api in ...

``There seems to be an issue with setting the input value attribute using jQuery's .html

I've been trying to update the value attribute in the input element within my HTML code, but so far, I haven't had any luck with it. HTML: <div class='photo-info'> Photo Name : <span class='photo-name'><?p ...

Creating a custom function in JavaScript to interact with the `windows.external` object specifically for use

In my current project, I am facing an issue with JavaScript file compatibility across different browsers. Specifically, I have a JavaScript file that calls an external function (from a separate file) using windows.external, like this: windows.external.se ...

As I iterated over the Vehicles API data, I encountered an issue while trying to access specific Vehicle information. I received an error message stating "Cannot read property 'id' of undefined

Exploring the realms of Angular, with some experience in older versions, I find myself faced with a challenge involving two APIs - "/vehicles" and "/vehicle/{id}". The process involves fetching data from "/vehicles", iterating through it to match IDs, the ...

Futuristic routing in VueJS

I've been attempting to dynamically generate routes, but unfortunately I'm facing difficulties as it seems not feasible with Vuejs 3 import { createRouter, createWebHistory } from "vue-router"; import TopMenu from "../layouts/top-m ...

"Element UI, featuring a wide array of components, contributing to bloated bundle sizes

I was looking into the following link. After following the instructions, I realized I am using class based components. Therefore, I am importing as shown below: import {Checkbox} from 'element-ui'; @Component({ components: { Checkbox } }) e ...

Issue with thymeleaf causing malfunction in top-bar navigation on foundation framework

Looking for advice on creating a navigable menu using Foundation's "top-bar" component in an HTML template file with Spring MVC + thymeleaf. The menu bar appears but the sub-menus are not displaying when hovering over them. Sub-menus related to main ...