How to access callbackScope in function

Hi,

I’m using this timer event as an example. How do I access callbackScope when it’s passed to my callback function? In the example, it’s not being used.

In my create.js
// Check the store every 2 secs
let x = this.time.addEvent({
delay: 500,
callback: checkStore,
callbackScope: this,
loop: true
});

In checkStore.js

import { store } from "../index.js";
let currentValue;
export const checkStore = x => {
	console.log(this);
	let previousValue = currentValue;
	currentValue = store.getState();
	if (currentValue != previousValue) {
		console.log("something's changed");
		console.log(x);
		console.log(store.getState());
		this.callbackScope.physics.add.sprite(400, 150, "blankFlower");
	}
};

“This” and “x” my arguement are both undefined. How would I access the game from an external file?

Thank you for your help!

Hello @nodes777,
As far as i know es6 Arrow Functions doesn’t have a scope, that’s why your this is becoming undefined.
Can you try to turn your function like this:

function checkStore(x) {
	console.log(this);
	let previousValue = currentValue;
	currentValue = store.getState();
	if (currentValue != previousValue) {
		console.log("something's changed");
		console.log(x);
		console.log(store.getState());
		this.callbackScope.physics.add.sprite(400, 150, "blankFlower");
	}
};

Let me know if it’s work will you :slight_smile:

2 Likes

That was it! Perfect! Thank you! I get confused with all the different ways to bind this.

1 Like