views:

32

answers:

1

Hi, 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_id = canvas_id;
  bind_events()

  function bind_events(){
  $(get_canvas()).click(function(e){
    var canvas = get_canvas() //works
    do_something_in_the_instance_who_called_click()
  }

  function get_canvas(){return document.getElementById(canvas_id)}

  function do_something_in_the_instance_who_called_click(){ 
    alert(this.canvas_id) //fail!
  }

}

Because when the click() is invoked for what it looks this is not inside the instance anymore, but I need to change atributes from there.. is there a way, given that may be multiple instances?

I don't really know how but the get_canvas() works :)

I'm using jQuery but likely not relevant

+3  A: 

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

function DrawingTable(canvas_id){
  var instance = this;  // <-- store `this` value

  this.canvas_id = canvas_id;
  bind_events()

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

    var canvas = get_canvas();
    do_something_in_the_instance_who_called_click();
  }

  function get_canvas(){return document.getElementById(canvas_id)}

  function do_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.

CMS
+1 Great Great Explanation! Will just keep open for few more hours
Fabiano PS