1

I was trying to make a game using Vue + Vuex, but in the middle of the project I realised that the most interactive part of the game had to be made with Phaser, then I decided to use Phaser for that part and keep the Vue + Vuex for the UI.

Everything was going better than expected until I tried to get the first data from Vuex in Phaser, the problem is that I lose the scope of the current object.

I'm using store.watch(); to get the changes but When I try to call other functions I get an error.

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

In this code from Phaser the _newCreatureRX is called by VueX, when I try to call _addCreature I get an error telling that _addCreature is not defined. The console.log(this) shows an Vue object.

How do I get this to work properly? Do I Have to structure my project differently?

Drico
  • 119
  • 1
  • 5

1 Answers1

1

The store.watch method will not execute the callback function in the original context, that is why this is incorrect.

You can explicitly bind the function to the correct context though

store.watch(this._newCreatureGetter, this._newCreatureRX.bind(this))
Phil
  • 157,677
  • 23
  • 242
  • 245
  • That worked! Thanks! I didn't know that i could send a callback with .bind(this). It makes perfect sense now! – Drico Jan 23 '17 at 03:14
  • It's easy to miss. The problem is because in Vue.js, it executes the callback via `cb.call(vm, watcher.value)` where `vm` is the `Vue` instance. See https://github.com/vuejs/vue/blob/769c4dc2032251323c8f61ad8eba2c26c615a618/src/core/instance/state.js#L228 – Phil Jan 23 '17 at 03:30