2009-09-24 54 views
0
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... 
}); 

在我的dblclick(event)函數中,我想訪問我在「父對象」中聲明的函數makeCellEditor。訪問父javascript對象的變量和方法?

回答

3
var self = this; 
    cell.addEvent('dblclick', function (event){ 
        alert(this.innerHTML); // i can see this is the cell here. 
        self.makeCellEditor(this); 
      }); 
+0

感謝它的工作就像一個魅力! – jonaz 2009-09-24 13:11:22

1

可以在另外一個變量保存this參考,使其到事件處理程序訪問,這樣的事情:

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

    ... 

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

在事件處理器,this指細胞和self可用,通過一個封閉物,作爲對外部物體this的參考,SortingTable

0

您還可以通過追加.bind(this)來綁定匿名函數。和改變的「本」的類範圍,細胞已經包含對點擊的對象,你可以使用一個參考......

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)); 
} 

我傾向於這樣的解決方案,因爲它不涉及製作一個新的對整個類的引用(self = this),即使它是一個局部範圍,但有時它是不可避免的。

您還可以閱讀這個http://mootools.net/docs/core/Native/Function#Function:bindWithEvent