3

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);

}
2
  • 1
    this always refers to the caller of the method. I suspect your error lies beyond the code you've provided Commented Dec 18, 2015 at 21:33
  • 5
    When you call .addEventListener, use this.update.bind(this) instead of just this.update. Commented Dec 18, 2015 at 21:33

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.