2011-10-11 6 views
0

이제 캔버스 요소에 마우스 이벤트 리스너를 등록하려고합니다. 마우스 이벤트 리스너 및 "this"

내 JS 응용 프로그램 개체가 초기화 할

, 그것은 정의에 마우스 이벤트를 결합 "MouseController"클래스 :

this.canvas.addEventListener('mousedown',this.input0.btnDown, false); 

"이"초기화되는 응용 프로그램 객체이며, 캔버스에 기본 HTML5 캔버스에 대한 참조입니다 나의 페이지. 마우스 클릭

function MouseController(eventHandler) { 
this.handler = eventHandler; 

this.contact = false; 

this.coordX = 0; 
this.coordY = 0; 
} 

MouseController.prototype.btnDown = function(event) { 
// Faulty line ??? 
this.updateCoordinates(event); 
} 

MouseController.prototype.updateHIDCoordinates = function (event) { 
// code to set coordX and coordY of the controller instance 
// Again, I can't access the object from here as "this" refers to the Canvas 
} 

으로, 콘솔 로그는 " '표현의 this.updateCoordinates의 결과가 함수가 아닙니다"

컨트롤러는 같은 간단한 클래스입니다. 이전의 토론은 잃어버린 참조 "this"에 대해 가르쳐주었습니다.이 경우 캔버스 아이템에 묶여 있습니다.

그래서 Java에서와 같이 "btnDown"을 호출하는 방법을 찾고 있는데, 이것은 객체의 일부로 실행되며 따라서 해당 객체의 변수에 액세스 할 수 있음을 의미합니다.

내가 좋은 없음 :(나는 깨끗한 해결책이있을거야 ... 싱글이었다 발견 된 유일한 해결책은 ... 이

감사합니다 :-) 도와주세요! J.

답변

1

폐쇄 만들 다음 중 하나를

var controller = this.input0; 
this.canvas.addEventListener('mousedown', function(event){ 
    controller.btnDown(event); 
}, false); 

또는 인 ECMAScript 5의 .bind()[MDN]를 사용

this.canvas.addEventListener('mousedown', this.input0.btnDown.bind(this.input0), false); 

또 다른 방법은 updateHIDCoordinates하지 updateCoordinates라고 있습니다.

+0

니스, 도움이됩니다. – Jem

+0

내 btnDown이 호출 될 때 이상한 일이 생겨서 "this.handler.click()"이라고합니다. 응용 프로그램 개체의 "click()"메서드는 단순히 다음을 호출합니다. console.log ('click at'+ this.input0.coordX); input0이 멤버 변수로 설정되었습니다. 컨트롤러에서 돌아 오면, "handler.input0"은 null로 설정됩니다 ... 어떤 이유입니까? 감사합니다 – Jem

+0

흠, 이제 input0에 대한 참조가 다시 작동합니다 .. .wierd ... 나는 확실히 깨지 않고 뭔가를 깨뜨 렸습니다. 당신의 도움을 주셔서 감사합니다! – Jem