FAQ: Learn Phaser Basics: Color A Pegasus - Updating Color

Hello,

While the JavaScript functionality behind contexts and is better defined here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

One simple way to test the difference (or why we might use context) is by changing the color after we set the event handler.

For example, test the code using this:

    /* add a click handler for each palette circle here */
    paletteCircle.setInteractive()
    paletteCircle.on('pointerup',function(){
      gameState.selectedColor = this.color
      },{color})
    color = 0x000000;

Now hit “Run” and try painting. You will notice that we are still painting with the correct color selected from the palette, that is, changing the color to 0x000000 below did not change the color we are painting with.

However, if we remove the context and try this instead:

    /* add a click handler for each palette circle here */
    paletteCircle.setInteractive()
    paletteCircle.on('pointerup',function(){
     gameState.selectedColor = color 
    })
    color = 0x000000;

Then hit “Run” and try painting and changing colors, we will notice that every color we select now paints black.

Ok, from that we can say that using “color” directly will use the current value of color (even if we changed it after setting the ‘pointerup’ event handler.) However, using the context will preserve the value of the colors defined above, so if we changed the value of color after that, the event handler will use the old value (or copy of the value).

So, if we don’t want to change the value afterwards, using the context seems like a good idea. Otherwise, if we want to change those colors by changing the color variable after (below) setting up the event handler, we don’t need to use the context.

In this lesson, it will work the same either way because we aren’t changing the color variable below the event handler code.

I hope the description is helpful.

9 Likes