What is the best way to invoke a component method from an event listener of a different component using ($on)?

I recently came across information on Non-Parent-Child Communication at https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication, which explains the concept of using bus events to communicate between components.

However, I'm still unsure about how to call methods from other components within a bus listener. For example, how can I invoke lst.additem2() from eventHub.$on('lst:additem', function()? It seems like the context of this inside that function refers to the eventHub instead (as indicated by the console.log( this.$data) result).

Here is an example code snippet:

Vue.component('lst', {
template: `
   <ul>
     <li v-for="(item, index) in items" :good='item' :key="item.id">
       <item :it='item' :index="index" ></item>
     </li>
   </ul>`,
created: function () {
  this.eventHub.$on('lst:additem', function(d) { 
    console.log( d );
    console.log( this.$data.tip );
    // this.additem2(d); this won't work :(
  });
},
methods: {
  additem2 : function(newitem) {
    console.log( '...here '+newitem.weight );
    this.items.push( newitem );
    console.log( 'item added' );
  }
}

For more details, you can visit this JSFiddle link: https://jsfiddle.net/0mx8mtcj/13/

Answer №1

During your listening session:

  this.eventHub.$on('lst:additem', function(d) { 
    // Use `this` to refer to the bus instance
  });

To ensure a smooth process, remember to store a component reference:

var self = this;
this.eventHub.$on('lst:additem', function(d) { 
  self.additem2(d);
});

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

Enhancing leaflet popup functionality by incorporating ng-click into the onEachFeature function

After creating a map and connecting it with my geojson api, I encountered an issue when trying to link each marker popup with ng-click. Simply adding HTML like this did not work as expected: layer.bindPopup("<button ng-click='()'>+feature. ...

What is the best way to decrypt a Bcrypt-hashed password for the purpose of displaying it?

Currently developing an application that enables users to log in using a username/password combination. I have set up an Administrator account responsible for creating these user accounts, with the passwords being hashed before storing them in mySQL DB. Ho ...

Leveraging the reset function with the $meteor.object

Currently, I am working on a straightforward controller utilizing the angular-meteor starter project. controller("PartyDetailsCtrl", function($scope, $stateParams, $meteor) { $scope.party = $meteor.object(Parties, $stateParams.partyId); $scope.save = ...

Multiple tabs open with inactive sessions

I am currently facing an issue regarding user idle timers in jQuery. I have implemented a timer that logs the user out of the app if they are inactive for 30 minutes, and this works perfectly with one browser tab open. However, I now need to extend this ...

Vue Bootstrap toaster that magically disappears in an instant

My Vue Bootstrap Web-App (v2.21.2) is designed to utilize Toasts for displaying errors generated by the REST API client to users. When errors are caught in my components, a function is called that uses this.$bvToast.toast() to dynamically generate and dis ...

What is the best way to display a JavaScript loop on a webpage instead of just in the console?

As a beginner in programming, I have taken on the challenge of creating my own FizzBuzz program. The goal is to write a program that displays numbers from 1 to 100. However, for multiples of three, it should output "Fizz" instead of the number; for multipl ...

Refresh in AJAX, automated loading for seamless transition to a different page

Having an issue with the page not auto-refreshing, although it loads when I manually refresh. P.S Loading the page onto another page. Below is my HTML and AJAX code along with its database: The Trigger Button <?php $data = mysqli_query ...

What is the process for changing the background color when a button or div is pressed, and reverting the color back when another button or div is

Looking to customize a list of buttons or divs in your project? Check out this sample layout: <button type="button" class="btn" id="btn1">Details1</button> <button type="button" class="btn" id="btn2">Details2</button> <button ty ...

Updating the DOM using jQuery after receiving an AJAX response

I'm grappling with the most effective way to modify the DOM after receiving an AJAX response. I prefer to showcase the code rather than attempt to articulate my dilemma. // page contains several checkboxes $("input[type='checkbox']").live(& ...

Effectively controlling two distinct Azure resources within one domain name through domain routing

I am currently in the process of deploying a React application on Microsoft Azure that includes a basic content management feature. Essentially, when users visit the website and access static content, the app retrieves HTML code from a database and display ...

What is the best approach for migrating event bus functionality to Vuex store?

At the moment, I have set up an event bus to trigger methods in specific Vue components from other unrelated components. With a fully functional Vuex store in place, my goal is to eliminate the need for the event bus and transition this functionality to t ...

What is the best way to obtain the present date in Nuxt directly from the server?

While conducting code tests, I realized that I required the current time from the server to run the tests effectively. In JavaScript, you can easily obtain the current date on the client side using the command: new Date();. However, when working with Nuxt ...

Text inside the placeholder is not displaying correctly in the React.js user interface

When passing placeholder text as a prop to the <FormField/> component from the <CreatePost/>, I encountered an issue where the placeholder text was not displaying in the form. Interestingly, when I used console.log within the <FormField/> ...

Playwright failing to execute GraphQL tests due to TypeScript configuration problems

I'm facing an issue with my repo where I am running tests using Playwright against a graphQL URL. Despite configuring the tests, there is an error indicating that the environment variable defining the environment cannot be found. The repository in qu ...

How can JavaScript be used to parse an XML file? Should we consider using SAX for handling large XML files

Hello everyone, I am feeling very frustrated and overwhelmed with my current situation. I have been searching everywhere for a solution but seem to be going in circles. This will be my first attempt at working with xml and it's quite daunting, espec ...

Activate the download upon clicking in Angular 2

One situation is the following where an icon has a click event <md-list-item *ngFor="let history of exportHistory"> <md-icon (click)="onDownloadClick(history)" md-list-avatar>file_download</md-icon> <a md-line> ...

Is it possible to run my NPM CLI package on CMD without needing to install it globally beforehand?

I've created a new NPM package, complete with its own set of CLI commands. Let's call this package xyz, and let's imagine it's now live on npmjs.com Now, picture a user who installs this package in their project by executing npm insta ...

Adjust the height of an element when an animation is initiated (Angular)

Check out the transition I've set up to smoothly slide between my views: https://plnkr.co/edit/yhhdYuAl9Kpcqw5tDx55?p=preview To ensure that both 'panels' slide together, I need to position the view absolutely. However, this causes the view ...

Is TypeScript being converted to JavaScript with both files in the same directory?

As I begin my journey with TypeScript in my new Angular project, I find myself pondering the best approach for organizing all these JS and TS files. Currently, it appears that the transpiler is placing the .js files in the same directory as the correspondi ...

Creating a smooth animated scroll to a specific #hash while keeping elements hidden on the page

I'm facing an issue with a JavaScript function that scrolls to a selected element with scroll animation. Everything is working fine, however, I encounter a problem when sliding up or down to show/hide certain elements. When a clicked link contains th ...