2012-01-17 5 views
0

원래의 코드를 바인딩 :jQuery를 :하여 addEventListener에서 전환

this.control.addEventListener('click', $.proxy(function() { 
    this.time.hashours = (this.duration()/3600) >= 1.0; 
    this.time.duration.text(getTime(this.duration(), this.controls.time.hasHours)); 
    this.time.current.text(getTime(0, this.controls.time.hasHours)); 
}, this)); 

크로스 브라우저 지원에서 시도 : 심지어 프록시

$(this.control).bind('click', $.proxy(function(e) { 
    var o = e.delegateTarget; 
    o.time.hashours = (o.duration()/3600) >= 1.0; 
    o.time.duration.text(getTime(o.duration(), o.controls.time.hasHours)); 
    o.time.current.text(getTime(0, o.controls.time.hasHours)); 
}, this)); 

이의 상황이 더 이상에 속하는 없다 jQuery의 커스텀 이벤트 모델 때문에 객체를 호출한다. 원본 this.control을 얻으려면 어떻게해야합니까?

답변

2

는,이 문맥은 더 이상 때문에 jQuery의 정의의 호출하는 객체에 속하는 :

또한, 단지 참고로, jQuery를 1.7로, .on 방법은 .bind 참조 선호한다 이벤트 모델.

jQuery의 사용자 지정 이벤트 모델이 여기에있는 문제라고 생각하지 않습니다. 콜백 함수를 프록시 할 때 this 값은 원래 예제에서와 같이 controlctimetime과 같은 다른 속성을 포함하는 루트 개체를 참조해야합니다. 즉

은이 최소한의 example 유사

this.time.hashours = (this.duration()/3600) >= 1.0; 

체크 아웃을 delegateTarget

var o = e.delegateTarget; 
o.time.hashours = (o.duration()/3600) >= 1.0; 
... 

에서 다음과 같이 원래의 객체를 얻으려고하지만, 그냥 원래의 코드에 충실하지 않습니다 너의 구조.

+1

당신 말이 맞아요. '.bind' 대신'.on'을 사용하면'$ .proxy'와 함께 작동합니다. –

+0

@BrianGraham -'bind'와'on'은이 특별한 예제에서 기능적인 차이점이 없습니다. 아마 그 실수를 일으키는 다른 것이었을 것입니다. – Anurag

0

이 질문에 대한 답변을 모르겠지만 jQuery의 사용자 지정 이벤트 개체에는 원래 이벤트가 포함되어 있습니다. 다음과 같이 액세스 할 수 있습니다. e.originalEvente은 jQuery 이벤트입니다. http://api.jquery.com/bind/ 심지어 프록시와

+0

'var o = e.originalEvent;'를 사용하면'o.time'은 정의되지 않습니다. –

+0

좋은 지적. 나는 @ Anurag의 대답이 당신이 찾고있는 것이라고 생각합니다. –

0

이벤트 핸들러에서 this.control을 사용하려면 다음과 같이해야합니다.

var $context = this; 
$(this.control).bind('click', function(e) { 
    //You can use $context here 
    //var o = e.delegateTarget; 
    $context.time.hashours = ($context.duration()/3600) >= 1.0; 
    $context.time.duration 
    .text(getTime($context.duration(), $context.controls.time.hasHours)); 
    $context.time.current.text(getTime(0, $context.controls.time.hasHours)); 

    //And this will point to this.control on which the event is triggered 
});