Skip to content Skip to sidebar Skip to footer

Bound Click Loses Context Of My Class. Js

I have this problem that I probably understand but don't know how to handle, if there is a way. I have a class simplified as this: function DrawingTable(canvas_id){ this.canvas_i

Solution 1:

That happens because you are calling the function without any object context, but you can store the this value:

functionDrawingTable(canvas_id){
  var instance = this;  // <-- store `this` valuethis.canvas_id = canvas_id;
  bind_events()

  functionbind_events(){
  $(get_canvas()).click(function(e){
    // Note also that here the `this` value will point to the // canvas elemenet, `instance` should be used alsovar canvas = get_canvas();
    do_something_in_the_instance_who_called_click();
  }

  functionget_canvas(){returndocument.getElementById(canvas_id)}

  functiondo_something_in_the_instance_who_called_click(){ 
    alert(instance.canvas_id); // <-- use stored `this` value
  }

}

The this value is implicitly set when you make a function call, for example:

obj.method();

The this value will point to obj, if you make a function call without any base object, e.g.:

myFunction();

The this value inside myFunction will point to the global object.

Post a Comment for "Bound Click Loses Context Of My Class. Js"