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);
}
thisalways refers to the caller of the method. I suspect your error lies beyond the code you've provided.addEventListener, usethis.update.bind(this)instead of justthis.update.