[SOLVED] EventListener causes undefined error

I am trying to pause the app if the player rotates the phone or resizes the window in a vertical way.

In the following code, the “dimensions” function is successfully called but the code in it gives an error.
If I use the same function directly without using the events (e.g. if I call it on initialize) it works just fine.

var ResolutionManager = pc.createScript('resolutionManager');

ResolutionManager.attributes.add('PausePanel', {type : 'entity'});

// initialize code called once per entity
ResolutionManager.prototype.initialize = function()
{
    this.PausePanel.enabled = false;

    // On orientation change
    window.addEventListener("orientationchange", this.dimensions, false);
    // On resize
    window.addEventListener("resize", this.dimensions, false);
};

ResolutionManager.prototype.dimensions = function()
{
    var w = window.innerWidth;
    var h = window.innerHeight;

    if (w < h) //Portrait
    {
        this.app.timeScale = 0;
        this.PausePanel.enabled = true;
    }

    else //(w == h) Square// or //(w > h) Landscape//
    {
        this.app.timeScale = 1;
        this.PausePanel.enabled = false;
    }
};

Both these lines gives an error:

this.app.timeScale = 1;
this.PausePanel.enabled = false;

Uncaught TypeError: Cannot set properties of undefined (setting ‘timeScale’)
Uncaught TypeError: Cannot set properties of undefined (setting ‘enabled’)

What I am doing wrong?

Hi @Utkan_LavaLabs,

You need to set the context on your event handlers, you can do it like this:

    const callDimensions = this.dimensions.bind(this);

    // On orientation change
    window.addEventListener("orientationchange", callDimensions, false);
    // On resize
    window.addEventListener("resize", callDimensions, false);

Note how I use .bind(this) on the listener.

2 Likes

I see, thank you for the answer.
It worked perfectly :slightly_smiling_face:

1 Like