2017-01-23 4 views
1

Vue + Vuex를 사용하여 게임을 만들려고했지만 프로젝트의 한가운데서 게임의 가장 인터랙티브 한 부분을 만들어야한다는 것을 깨달았습니다. Phaser로, 그 부분을 위해 Phaser를 사용하고 UI를 위해 Vue + Vuex를 유지하기로 결정했습니다.Vue + Vuex + Phaser 반응 호출에서 'this'스코프가 끊어짐

Phaser의 Vuex에서 첫 번째 데이터를 가져 오기 전까지는 모든 것이 예상보다 좋았습니다. 문제는 현재 개체의 범위가 손실된다는 것입니다.

변경 사항을 적용하려면 store.watch();을 사용하고 있지만 다른 기능을 호출하려고하면 오류가 발생합니다. 내가 _addCreature가 정의되어 있지 않은 것을 말하는 오류가 _addCreature를 호출 할 때 페이저 _newCreatureRX에서이 코드에서

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

는 VueX에 의해 호출됩니다. console.log(this)에는 Vue 개체가 표시됩니다.

어떻게하면 제대로 작동합니까? 내 프로젝트를 다르게 구성해야합니까?

답변

1

store.watch 메서드는 원래 컨텍스트에서 콜백 함수를 실행하지 않으므로 this이 올바르지 않습니다.

당신이 할 수있는

명시 적으로 일

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

하지만 올바른 컨텍스트 기능을 bind! 감사! .bind (this)로 콜백을 보낼 수 있는지 몰랐습니다. 이제는 완벽하게 이해할 수 있습니다! – Drico

+0

놓치기 쉽습니다. 문제는 Vue.js에서'cb.call (vm, watcher.value)'를 통해 콜백을 실행하기 때문입니다. 여기서'vm '은'Vue' 인스턴스입니다. https://github.com/vuejs/vue/blob/769c4dc2032251323c8f61ad8eba2c26c615a618/src/core/instance/state.js#L228을 참조하십시오. – Phil