[SOLVED] Problem to use onClick button with HTML UI

Hi there,
I am actually working on a project where i got to import different HTML text.
To do this, i was following this project example : https://playcanvas.com/editor/scene/481136
All is working fine !

After this, I wanted to personalize the onClick function. There is my code :

PageContructor.prototype.setupNextButton = function() {
    var self = this;
    
    var button = this.div.querySelector('.button');

    if (button) {
        button.addEventListener('click', function() {
            console.log('button clicked');
            this.entity.script.scenario.nextStep();
                
        }, false);
    }
};

Problem is i got this error :
Uncaught TypeError: Cannot read properties of undefined (reading ‘script’) at HTMLDivElement.
In my script, it represents this line

this.entity.script.scenario.nextStep();

It looks like i can’t call entity in the event listener. Is there another way to call a canvas function in this event listener ?

Hi @antoinebao and welcome,

You are only missing setting the correct context at your event callback function, check the last here, I’m adding bind to do that:

        button.addEventListener('click', function() {
            console.log('button clicked');
            this.entity.script.scenario.nextStep();
                
        }.bind(this), false);
1 Like

Thanks a lot @Leonidas, that’s working !

1 Like