Utilize Vuex's $store.watch method to dynamically add and remove event listeners

Here's the section where I'm monitoring my store using mounted():

  this.$store.watch(
    (state, getters) => state.windowState && state.chatState == 0,
    (val, oldVal) => {
      if (val) {
        console.log('state is true')
        this.$refs.chatAuth.addEventListener('keydown', this.pressEnterChatAuth)
      } else {
        console.log('state is false')
        this.$refs.chatAuth = null
      }
    }
  )

windowState represents a boolean value, chatState represents a numerical value such as 0, 1, or 2.

In this scenario, even if windowState switches to true and chatState changes to 1, the event listener remains active. This issue has me puzzled. Can we actually use $store.watch for two states or getters simultaneously?

When chatState equals 1, I receive a console message saying "state is false", but the listener persists in spite of that.

My Analysis

I have a suspicion that once a watched value goes back to false, this.$refs.chatAuth might have been removed from the DOM. This element is conditionally rendered based on the chatState, so even though my else block runs and sets it to null, it may not have any effect as the element was already taken out from the DOM. If that's the case, then why does the listener continue to work?

Answer №1

Vue really came through for me with their native event listeners:

<div @keydown.enter.exact="pressEnterChatAuth" class="chat__auth"></div>

It's funny how clear the solution was, no need to mess around with addEventListener.

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

Backbone causes a sudden influx of unexpected AJAX requests

I included the fetch URL with a deferred method, expecting it to only make one remote AJAX request. However, I noticed that it is being called three times when the page loads. Does anyone know how to resolve this issue? Thank you JS Scripts var Commen ...

Calculating the total square footage divided by square feet and the annual rent divided by square feet using Javascript

I need help with running multiple calculations. One of them involves dividing the annual rent by the square feet. However, this calculation fails if a comma or dollar sign is included. I want the rent/sq ft field to display nothing instead of NaN if the fi ...

Incorporating additional options onto the menu

I recently designed a menu on https://codepen.io/ettrics/pen/ZYqKGb with 5 unique menu titles. However, I now have the need to add a sixth title to the menu. After attempting to do so by adding "strip6" in my CSS, the menu ended up malfunctioning and looki ...

Implementing CSS keyframes when a specified PHP condition is satisfied

I am looking to implement an opening animation on my website that should only play when a user visits the site for the first time. I want to avoid displaying the animation every time the page is reloaded, so it should only run if a cookie indicating the us ...

Trigger a JQuery function to run upon the pressing of the Enter key within a textbox

$(document).keypress(function(e) { if(e.which == 13) { $("#submitButton").click(); } }); That's how I'm triggering my function when the Enter key is pressed anywhere on a page, but it conflicts wi ...

What is the best way to transmit data from a single input to two separate APIs within a Next.js environment?

I am working on a registration page that includes an option for users to sign up for a newsletter by checking a box. The code below is what I currently have to handle the form submission: const handleSubmit = async e => { e.preventDefault() cons ...

Utilize the dimensions of one image to resize others using the JavaScript method .getBoundingClientRect

I am attempting to transfer the width and height measurements of the initial image to all subsequent images on the page. Currently, I have successfully applied the dimensions of the first image to the second one, but I am facing difficulties with the thir ...

Unable to access Vue component method beyond its scope

Having an issue with my Vue component that I'm trying to call a method from outside its wrapper element #app. Is there a way to register the component so I can easily call it like Component.function(); var viewController = new Vue({ el: "#app", ...

Can someone explain how to use JavaScript to make table data fill the entire row in a table?

After clicking the button, the layout of the table changes. I want to keep the original table layout even after the JavaScript function runs. I am still learning about JavaScript. function toggle(button) { if(document.getElementById("1").value=="Show ...

What is the simplest method for invoking a C# function from JavaScript?

I am facing an issue with a LinkButton control in my project. I need to attach a c# method to it, but when I add the control to the page using parse control function, it changes the call to javascript and results in an undefined error. I have been trying t ...

karma: Error: Unable to access the 'prototype' property of an undefined object

Whenever I attempt to inject my service, the following error occurs: (function () { describe('Test', function () { var $scope, $state, service,ctrl; beforeEach(function() { module('moduleApp'); ...

Is there a way to track the amount a user scrolls once they have reached the bottom of a page using Javascript?

It's a popular UI pattern on mobile devices to have a draggable element containing a scrollable element. Once the user reaches the end of the scrollable content, further scrolling should transition into dragging the outer element. For example, in this ...

How do I change the 'CSS Theme' of my website?

With Halloween approaching, I am eager to transform my website's BODY css into a spooky Halloween theme. The challenge is that my .Net pages are Templates. Is there a way for me to ensure that the body class checks for an existing CSS theme override? ...

Is there a way to adjust this callback function in order to make it return a promise instead?

This script is designed to continuously attempt loading an image until it is successful: function loadImage (url = '', callback = () => {}) { utils.loadImage(url, () => { callback() }, () => { loadImage(url, callback) }) } ...

Locating a user by their ID within a collection in Meteor can lead to some unexpected behavior

I have a requirement where I only want to allow users to insert a document if their email is verified. In an attempt to achieve this, I wrote the following code snippet. Events.allow({ insert: function (userId, doc) { var user = Meteor.users.f ...

Can anyone assist me with this HTML/jQuery code?

Despite my efforts, I've been unable to achieve success. The challenge I'm facing is with duplicating controls for adding images. I have a button and a div where the user can choose an image by clicking the button. The selected image appears in ...

How to retrieve the ID of the inserted record in Knex.js

I was trying to add a new note to the quoteNotes table. However, after inserting it and logging the response, I noticed that there was no record of the inserted note showing up. router.post('/:id/notes', (req, res) => { const {id} = req.para ...

Managing location markers with Google Maps API V3: Saving and removing locations

I encountered an issue while using GMAP V3. After realizing the need to save map changes in a database, I struggled to find a way to accomplish this task. Before attempting any workarounds, I thought it would be best to gather some ideas first. The communi ...

What is the best way to switch from using the three.js JSONLoader to the ObjectLoader?

I successfully loaded multiple files using the code below for three.js JSONLoader: <!DOCTYPE html> <html> <head> <title>Rotating Sphere</title> <meta charset="utf-8"> <!-- https://cdnjs.com/libra ...

What is preventing my Grails application from retrieving an object from my Angular script?

I'm currently working on adding objects to a JSON list in Grails. Below is the Angular code I am using: http://pastebin.com/4ypijUMD Additionally, here is my Grails controller: http://pastebin.com/skTtVtxv My understanding is that the angularJS scri ...