Managing events in VueJS

I am experimenting with VueJS to understand how to use emit and listen methods. I encountered some unexpected results that I cannot figure out. My expectation was for the initMap() function to be called and for the console to log the expected output, which it does, but an error message appears at the top of the page.

Uncaught TypeError: Cannot read property 'apply' of undefined
    at Vue$3.Vue.$emit (vue.js:2186)
    at Vue$3.emit (main.js:131)
    at Vue$3.boundFn [as emit] (vue.js:167)
    ...

SENDING

import GISView from './components/GISView.vue';
import VueEvents from 'vue-events';

window.Vue = Vue;
Vue.use(VueEvents)

var App = window.App = new Vue({
  el: '#app',
  components: {
    gisview: GISView
  },
  methods: {
    initMap: function() {
      this.$events.fire("MapLoaded");
    }
  }
});

LISTENING

<template>
    <div ref="map" id="map" class="google-map" style="position: relative; overflow: hidden;">
        <div style="height: 100%; width: 100%; position: absolute; top: 0px; left: 0px;">

        </div>
    </div>
</template>
<script>
    import GoogleMaps from '../mixins/GoogleMaps.js';

    export default {
        mixins: [GoogleMaps],

        data() {
            return {
                map: ''
            }
        },

        mounted() {
            this.$events.$on("MapLoaded", this.initMap());
        },

        methods: {
            initMap: function() {
                console.log("OK");
            }
        }
    }
</script>

Answer №1

When mounting the component, ensure to correctly call the initMap method by removing the parentheses at the end. Update your code like this: 

Here is the corrected version:

mounted() {
    this.$events.$on("MapLoaded", this.initMap);
}

Answer №2

Encountered a similar issue when I had a handler declared outside of the 'methods' block.
To clarify, the first approach did not yield the desired result.

export default {
    name: 'app',
    created() {
        EventBus.$off('change-tab');
        EventBus.$on('change-tab', this.changeTab);
    },
    changeTab( newTab) {
        // implement a smart solution here
    },
}

However, using this alternative method solved the problem:

export default {
    name: 'app',
    created() {
        EventBus.$off('change-tab');
        EventBus.$on('change-tab', this.changeTab);
    },
    methods : {
        changeTab( newTab) {
            // implement a smart solution here
        },
    }
}

Answer №3

One situation I encountered was when I forgot to include the second argument in this.$root.$emit('someEvent')

To resolve the issue, I added an empty object as the second argument like this:

this.$root.$emit('someEvent', {})
;

Interestingly, despite this error, the reactivity within the $on function remained intact.

Let me illustrate with this code snippet:

handleScroll() {
  //   console.log(e);
  this.$root.$emit("bodyScroll", {});
},

And in a different component:

 data() {
    return {
      scroll: false
    };
  },
 mounted() {
    this.$root.$on("bodyScroll", data => {
      console.log("Receiving events", data);
      this.scroll = true;
    });
  },

Surprisingly, even with the error, the scroll event still functioned properly.

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

Guide to showing MySQL data on an HTML page using NodeJS

Currently delving into Node JS, I am faced with the challenge of displaying fetched data from my MySQL Table in an HTML table format. Despite my efforts, I have yet to find a solution that works for me. Any help or guidance on how to resolve this issue wou ...

Changing the input value in Nuxt / Vue 2 after it has been overridden

I'm working on a feature where the user's typed keys are converted to the last single upper-cased character (for example, 'a' becomes 'A', 'abc' becomes 'C'). Here is my current code snippet: <template& ...

Creating an HTTP interceptor in Backbone: A step-by-step guide

After gaining experience with backbone, I decided to delve into learning angular. The features of angular really caught my interest, especially the HTTP interceptor. I began thinking about how to implement this functionality in backbone to display a spin ...

Using JavaScript, generate ten clickable circles on the screen. Each circle should display the number of times it has been clicked in the center when interacted with

I am currently working on my JavaScript skills and would like to implement a fun project involving 10 colorful circles. While I can easily create these circles using HTML and CSS, I require assistance with the interactive functionality using JavaScript. ...

Unable to retrieve data from file input using jQuery due to undefined property "get(0).files"

I am facing an issue with retrieving file data in jQuery AJAX call from a file input on an ASP.NET view page when clicking a button. HTML <table> <td style="text-align:left"> <input type="file" id="AttachmenteUploadFile" name="Attachme ...

What is the reason that when a <div> click on a mobile device includes a jQuery ('#item').fadeOut() function, the CSS of the '#item' element maintains its previous hover state

While creating a mock back to top button, I encountered an issue with my jQuery call to fadeOut() behaving differently on mobile devices (this discrepancy can be observed using any desktop browser simulator). You can find the source code here: https://cod ...

An error was encountered when attempting to reference an external JavaScript script in the document

Could someone please provide guidance on how to utilize the document method in an external .js file within Visual Studio Code? This is what I have tried so far: I have created an index.html file: <!DOCTYPE html> <html lang="en"> <head> ...

Looking for specific characters in a string within an array of objects: a guide

In the example below, I have an array of objects containing raw data const data = [ {id:1, sItem:"This is javascript", status:"trending"}, {id:2, sItem:"javascript is fun", status:"trending"}, {id:3, sItem:&quo ...

Is it expected to conceal children who are 2 years old?

I came across the following HTML code snippet: <ul id="product_create-header" class="stepy-header"> <li id="product_create-head-0" class="stepy-active"> <div>Categoría</div><span>Categoría</span> </ ...

Animating the first element using Semantic UI React Transition Group

Is there a way to modify Semantic's Transition.Group example (found at ) to animate the topmost element instead of the bottommost one? In the example provided, pressing the add or subtract button results in the animation applying only to the last ele ...

Hide CSS background with React onclick

This particular div is responsible for creating a red box. However, my goal is to remove it upon clicking. I attempted to use state to achieve this functionality but unfortunately, it did not work as expected. import React, { Component } from "react"; ...

When I implemented snap.js on my main content wrapper, I noticed that it was causing a disruption in a few of my jQuery functions

Currently, I am utilizing snap.js to allow the sliding of the main content div using css3 and javascript, exposing a menu beneath. However, I am encountering an issue when I apply the class snap-content to specify which div snap.js should slide - which is ...

The Angular promise refuses to resolve at my desired time

I am struggling with managing Angular promises in order to control when they resolve. In the code snippet below, my intention is to first retrieve KeyDataFromServer() and then proceed with executing the remaining commands only after all the keys have been ...

The PHP-generated table is not being appended to the specified div with jQuery

I am currently working on developing a webpage that displays live forex rates to users. I am pulling the values from a feed and echoing them into a table. My goal now is to use jQuery to show this table to the user. The issue I am facing is that when I tr ...

Trouble getting a sticky element to align with a two-column grid within a parent container

I'm looking to keep one column sticky in a two-column grid setup. My goal is to create a vertical navigation bar that's specific to a particular div within a single-page site, with a fixed horizontal navbar across the entire page. However, I&apos ...

Issues with dynamically loading jQuery arise specifically on certain websites

Code: initializeJQuery(); function initializeJQuery() { if (typeof jQuery === "undefined") { var scriptElement = document.createElement('script'); scriptElement.setAttribute("type", "text/javascript"); scriptElement.setAttribute("sr ...

Tips on how to correctly pass a .JSON object in the setState function of a reactJS

I am having an issue when attempting to pass a .json file in the following format: this is my class import MyForm from './MyForm'; class CreateProject extends React.Component{ constructor(){ super(); this.state = { categori ...

Issue with utilizing display: table and overflow: hidden in Internet Explorer and Firefox, functioning properly on Webkit and Blink

JSFiddle : http://jsfiddle.net/h7xvr2t9/2/ I have been experimenting with ways to achieve some effects: Animating a hidden DIV to slide into view from below a visible container Centering text/image on a link to trigger the animation HTML <div clas ...

Is the target="_blank" attribute malfunctioning in Google Chrome?

Whenever I click on this text, it is supposed to display a base64 source image. However, this feature does not seem to be working in Chrome. The tag opens a new tab, but the href attribute is not present in the URL. Below is my HTML code: <div> & ...

Checking email existence through remote jQuery validation

Utilizing the jQuery validator plugin, I am implementing an ajax function with a remote method to validate whether an email already exists in my database. However, I am encountering an error when making the ajax call within my validation function. "email ...