Uncaught TypeError: Cannot read property 'enabled' of undefined

I have a Button in my scene and when I click it I want it to enable an Image element.
I have added this code to my button:

var Plattegrond = pc.createScript('plattegrond');

Plattegrond.attributes.add('textObject', {type: 'entity'});


// initialize code called once per entity
Plattegrond.prototype.initialize = function() {
    
    this.entity.element.on('click', function(e) {
  
    if (this.textObject.enabled === true)
    {
         this.textObject.enabled = false;
    }
     else
    {
        this.textObject.enabled = true;
    }
   
    });
   
};

// update code called every frame
Plattegrond.prototype.update = function(dt) {
    
};

// swap method called for script hot-reloading
// inherit your script state here
// Plattegrond.prototype.swap = function(old) { };

// to learn more about script anatomy, please read:
// https://developer.playcanvas.com/en/user-manual/scripting/

I get this error when I click on the button: “Uncaught TypeError: Cannot read property ‘enabled’ of undefined”

What am I missing here?

Hi @Maarten_deVries,

Have you referenced an entity in the textObject attribute in editor? If not then the error is correct, you can’t access a property of the this.textObject attribute.

Yes I have parsed the code and then selected an entity.

Right, my bad, I didn’t see your code, you are missing the right context in your event handler. You can use bind(this) to add it, so this refers to the script context:

    this.entity.element.on('click', function(e) {
  
    if (this.textObject.enabled === true)
    {
         this.textObject.enabled = false;
    }
     else
    {
        this.textObject.enabled = true;
    }
   
    }.bind(this));

(notice the last line)

1 Like