2009-09-24 3 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 (이벤트) 함수에서 "부모"개체에서 선언 한 makeCellEditor 함수에 액세스하고 싶습니다. this 셀을 참조하는 이벤트 핸들러 내부부모 자바 스크립트 개체의 변수 및 메서드에 액세스하고 있습니까?

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

    ... 

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

self 사용할 수 있습니다 :

답변

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

1

당신은, 이벤트 핸들러가 액세스 할 수 있도록 만들 또 다른 변수에 이런 일을 this 참조를 저장할 수 있습니다 , 클로우즈를 개입시켜, 외부 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)); 
} 

... 당신이 사용할 수있는 클릭 개체에 대한 참조를 포함 전체 범위 (자체 = this)에 대한 새로운 참조. 지역 범위 일지라도 때로는 피할 수없는 경우도 있습니다.

당신은 또한 마법처럼 일이 http://mootools.net/docs/core/Native/Function#Function:bindWithEvent