Binded click loses context of my Class. JS

Posted by Fabiano PS on Stack Overflow See other posts from Stack Overflow or by Fabiano PS
Published on 2010-06-15T14:10:07Z Indexed on 2010/06/15 14:12 UTC
Read the original article Hit count: 212

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

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about object-oriented-design