views:

151

answers:

3
var SortingTable = new Class({
          initialize: function( table, options ) {
               this.table=$(table);
               this.tbody = this.table.getElement('tbody');
               //...do alot of things here... 
        },
          addTextInput : function(index,headid,options){
            var trs = this.tbody.getChildren();
            var trslen = trs.length;
            var i=0;
            var cell = null;
            for(i=0;i<trslen;i++){
                cell = trs[i].getChildren()[index];
                cell.addEvent('dblclick', function (event){
                      alert(this.innerHTML); // i can see this is the cell here. 
                      this.makeCellEditor(this); // how to access the parent object? 
                });
            }
          },
           makeCellEditor : function(cell){
              //make form and stuff here.   
          }
    //...alot of more functions... 
});

In my dblclick(event) function i would like to access my function makeCellEditor that i've declared in the "parent" object.

+2  A: 
   var self = this;
   cell.addEvent('dblclick', function (event){
                  alert(this.innerHTML); // i can see this is the cell here. 
                  self.makeCellEditor(this);
            });
Locksfree
Thanks it worked like a charm!
jonaz
A: 

You can save the this reference in another variable to make it accessible to the event handler, something like this:

addTextInput: function(...) {
  var self = this;

  ...

  cell.addEvent('dblclick', function(event) {
    self.makeCellEditor(this);
  });
}

Inside the event handler, this refers to the cell and self is available, via a closure, as a reference to the outer this object, the SortingTable.

John Kugelman
A: 

you can also bind the anonymous function by appending .bind(this); and change the scope of 'this' to the class, cell already contains a reference to the clicked object that you can use...

for(i=0;i<trslen;i++){
    cell = trs[i].getChildren()[index];
    cell.addEvent('dblclick', function (event){
          alert(cell.get("html")); 
          this.makeCellEditor(cell); 
    }.bind(this));
}

i tend to favour this kind of a solution as it does not involve making a new reference to the whole class (self = this), even if it's a local scope but sometimes it's unavoidable.

you can also read this http://mootools.net/docs/core/Native/Function#Function%3AbindWithEvent

Dimitar Christoff