Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript class properties not available in onclick method

Tags:

javascript

Every time that I click the canvas that is created with this code, it always says that this.element is undefined when it clearly has been created. The graph that I am displaying is showing up, that is not the problem. If I replace this.element with document.getElementById(id), the code will work as intended. Any help or explanation is greatly appreciated, thanks.

function DrawableChart(id){

    // get canvas
    this.element = document.getElementById(id);
    this.ctx = this.element.getContext("2d");

    // set data
    this.data = {...};

    // special options
    this.options = {...};

    // create chart
    this.chart = new Chart(this.ctx).Line(this.data, this.options);

    // updating chart
    this.update = function(e){
        // this is where the error is
        console.log(this.element);
        // this line also causes an error
        var rect = this.element.getBoundingClientRect();
        var x = e.clientX - rect.left;
        var y = e.clientY - rect.top;
    };

    // update when clicked
    this.element.addEventListener('click', this.update);

}
like image 218
Zach P Avatar asked Jun 20 '26 23:06

Zach P


1 Answers

It's an issue with the update method and this value. Try changing the following:

this.update = function(e){ /*...*/ };

to:

this.update = function(e){ /*...*/ }.bind(this);
like image 121
Louay Alakkad Avatar answered Jun 22 '26 14:06

Louay Alakkad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!