2012-11-17 1 views
1

자바 스크립트 개체의 일부로 이벤트 처리기 함수를 사용하고 싶습니다. 이벤트 핸들러 내부의 "this"는 대개 이벤트가 발생한 객체에 자동으로 할당되므로 이벤트 처리기 내부의 "this"를 객체에 바인딩하려고합니다. 이벤트 처리를위한 javascript object-method의 바로 바인딩

는 바인딩이 발생하는 오브젝트 ( jsfiddle for tryout)에 대한 init 함수를 사용하여 수행 할 수 있습니다 :

var myObject = { 
    init:function(){ 
     this.downHandler = this.downHandler.bind(this); 
    }, 
    downHandler:function(){ 
     alert(this.someInfo); 
    }, 
    someInfo:"hi there" 
}  
myObject.init(); 

내가이 문제를 방지하려면 : 그것은 다른 곳에서 코드를 유지 보수를 decreses 재정의. 그래서 저는 메소드 자체에서 바인딩 프로세스를 유지하는 솔루션을 찾고 있습니다.

즉각적인 실행을 시도했지만 즉시 실행 지점에서 "this"는 "window"객체를 가리 킵니다 (브라우저 컨텍스트를 가정 함). 내 시험은 다음과 같이 :

var myObject = { 
//more code 
    downHandler:(function(){ 
     alert(this.someInfo); 
    }).bind(this), //does not work since at the point of immediate execution, the this is assigned to window 
//more code 
}  

당신은이 이벤트 처리 기능에서이 아닌 별도의 초기화 함수에 바인딩을 유지하는 방법을 생각할 수 있는가? 이미 jQuery를 사용을로드있어 한 이후

+0

밑줄과 같은 라이브러리를 사용 하시겠습니까? – tkone

+0

이미 jquery와 mootools가 있으므로 추가 라이브러리를 피하려고합니다. – JanD

답변

2

jQuery.proxy

var myObject = { 
    downHandler: $.proxy(function(){ 
     alert(this.someInfo); 
    }, this) 
}; 

당신은 Underscore

Mootools의가있을 수 있습니다 _.bind

var myObject = { 
    downHandler: _.bind(function(){ 
     alert(this.someInfo); 
    }, this 
}; 
사용, (나는이 같은 물건을 선호하는)가 설치되어있어 경우 비슷한 점도 있습니다.

+0

문제는 init 함수가 필요하다는 것입니다. 왜냐하면 초기화 시점의 "this"는 함수가 속한 객체가 아니라 전역 객체를 가리키기 때문입니다. 그러나 그것은 올바른 방향으로 나아갑니다 ... 내가 그것을 만들 수있는 것을 볼 수 있습니다 :-) – JanD

0
var myObject = { 
    clickHandler: function() { 
     alert(myObject.someInfo); 
     //returns undefined without execution of init-function 
     //returns "hi there" if init ran. 
    }, 
    someInfo: "hi there" 
} 

$('#clickMe').on('click', myObject.clickHandler); 
0

경고 사용 중에 'this'대신 'myObject'를 사용하십시오.

var myObject = { 
    downHandler:(function(){ 
     alert(myObject.someInfo); 
    }).bind(this), 
    //when 'this' use it alert undefined 
    //when 'myObject' use it alert "hi there" 
    someInfo:"hi there" 
} 

이 정보가 도움이되기를 바랍니다.

+0

감사합니다. 문제는이 값을 하드 코딩하면 "this"에있는 유용한 특성이 제거됩니다. 방법 등을 빌릴 수있다. – JanD