The challenge of losing the 'this' scope during a Vue + Vuex + Phaser reactive call

During my attempt to develop a game using Vue + Vuex, I encountered an interesting challenge. I realized that the most interactive aspect of the game needed to be built with Phaser instead. As a result, I made the decision to utilize Phaser for that specific part while continuing to use Vue + Vuex for the user interface.

Initially, everything seemed to be progressing smoothly until I attempted to retrieve data from Vuex within Phaser and encountered an issue with losing the scope of the current object.

I utilized store.watch(); in order to monitor changes but faced difficulties when trying to call other functions, resulting in errors.

import store from '../vuex/store';
import Creature from './Creature';
const creatures = [];
export default {
  create() {
    store.watch(this._newCreatureGetter, this._newCreatureRX);
    for (const creature of this._creaturesGetter()) {
      this._addCreature(creature);
    }
  },
  _addCreature(creature) {
    creatures.push(new Creature(this.game, creature));
  },
  _newCreatureGetter() {
    return store.state.newCreature;
  },
  _newCreatureRX(newCreature) {
    console.log(this);
    this._addCreature(newCreature);
  },
};

Within this snippet of code from Phaser, _newCreatureRX is called by Vuex. However, upon trying to execute _addCreature, I encountered an error indicating that it was not defined. The console.log(this) revealed a Vue object.

How can I resolve this issue and ensure proper functionality? Should I consider restructuring my project?

Answer №1

When using the store.watch method, keep in mind that the callback function will not run in its original context. This is why referring to this directly may lead to errors.

To ensure that the function executes in the desired context, you can use the bind method.

store.watch(this._newCreatureGetter, this._newCreatureRX.bind(this))

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

Having trouble decoding a cookie received from a React.js front-end on an Express server

When using React js for my front end, I decided to set a cookie using the react-cookie package. After confirming that the request cookie is successfully being set, I moved on to configure the Express server with the cookie parser middleware. app.use(cookie ...

Script CSP was declined from loading

After implementing CSP on my Nuxt website successfully, I encountered an issue when I added addMeta:true to the CSP object. This resulted in the following error message: https://i.sstatic.net/H5eTn.png Error message received: Refused to load the script ...

Can you provide guidance on how to use Javascript to submit a form specifically when the input name is labeled as "submit"?

Query: How can I use Javascript to submit a form when one of the form inputs is named submit? Scenario: I need to send users to another page using a hidden HTML form. Unfortunately, I cannot modify the names of the inputs in this form because it needs to ...

The act of loading a webpage without inserting any data into the database is not recommended

I've created an enroll.html page with the following code: <HTML> <HEAD> <script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></scr ...

Transform leaflet marker plugin into Typescript format

I recently discovered a leaflet extension that conceals map markers if they fall outside the boundaries of the current view map. import L from 'leaflet'; L.Marker.MyMarker= L.Marker.extend({}).addInitHook(function (this: ILazyMarker) { this ...

My controller in AngularJS is having trouble fetching the latest values of the $scope variables

In my code, I've included the relevant snippet below. The base angularJS seems to be functioning properly as the HTML document doesn't display {{}} variables but instead remains blank. I suspect that this is due to the variables receiving a null ...

Implementing form validation for dropdown lists with Material-UI React: A comprehensive guide

I'm still learning React and I've been using material-ui for form validation. Everything was going smoothly until I encountered an issue with validating a dropdown list. Whenever I try to validate it, an error occurs: "Cannot read property ' ...

Creating dynamic and stylish web interfaces using SCSS in conjunction with

I've incorporated <style lang="scss"> into my Vue single file components. However, in each component where I use my color variables, I have to import the file like this: @import "./../../../sass/variables";. I'm currently using Laravel Mix ...

The reactjs-toolbox radio button group remains unchanged

In my React application, I have implemented radio buttons using the following code: <RadioGroup name='steptype' className={css.ProcessStepRadioButtons} value={this.state.stepsData[stepNumber].stepType} onChang ...

What is the mechanism behind JQuery Ajax?

Currently, I am attempting to utilize JQuery Ajax to send data to a Generic Handler for calculation and result retrieval. Within my JQuery script, the Ajax request is contained within a for loop. The structure of the code resembles the following: function ...

Using Javascript Regex to conceal non-ASCII characters in strings

I'm currently working on masking strings using JavaScript regex. However, I've encountered an issue with non-ascii characters. How would you suggest resolving this problem? Below is the code I've been using: var name = "Üsüaüü Bxbd ...

Convert a single object into a JSON string representation on each line

Can you convert the following data into the desired format through stringification? Data: let result = JSON.stringify([ { "Color": "Red", "Type":"Fast" }, { "Color": "Blue&quo ...

Tips for establishing a connection between a Node.js application and PostgresSQL hosted on Heroku

I have utilized Vue, webpack, Express and PostgresSQL in the development of my app. After deploying my app to Heroku, I established a PostgresSQL database on the platform. In the image below, you can find the Database Credentials: https://i.sstatic.net/aI2 ...

Is a Toolbar plugin or custom Toolbar options the better choice for your project?

Could anyone recommend a Jquery plugin for adding a ToolBar option to my web application? I've searched and researched for the past 48 hours but haven't found a reliable one yet. If the recommended toolbar resembles the image below, that would b ...

Integrating Dialogflow with a Heroku JavaScript application

After extensive research, I delved into the realm of integrating DialogFlow requests with a webhook hosted on platforms like Heroku. With both Heroku and nodeJS impeccably installed on my system, I diligently followed the heroku tutorial to kickstart the p ...

Exploring AngularJS capabilities in showing server validation messages along with creating dynamic forms

On the server side, I am utilizing Express along with sequelizejs. Let's say we have this particular view: (It is included as <div ng-include src="'views/users/_form.html'"></div> in the new, edit view.) <div class="form-gro ...

Transferring data from a child component to a parent component

In my Nuxt UI component, I have the following code: <template> <div> <label for="phone" class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300">{{ $t('nav.cellphone') }}</la ...

The background image shifts dynamically with a parallax effect as the page is scrolled

I need help solving a parallax issue that I'm currently facing. On my webpage, I have a background image positioned at the top with a parallax effect achieved through background-position: fixed. However, I now require the image to scroll along with t ...

Enable Row Editing with a Click in Material Table

Utilizing the material-table library, I am implementing a feature to enable table rows to be editable upon double-click. The goal is for clicking on a row to trigger the same action as clicking the edit button located in the actions column on the leftmost ...

User has logged out, triggering the browser tab to close automatically

Is it possible to automatically log out the user when all browser tabs are closed? How can I obtain a unique ID for each browser tab in order to store it in local storage upon opening and remove it upon closing? Here is what I have attempted: I am utiliz ...