2010-05-19 2 views
8

jquery에서 이벤트 보유자의 바인딩은 DOM 요소를 생성하는 이벤트입니다 (dom 요소를 가리킴). 프로토 타입에서 이벤트 핸들러의 바인딩을 변경하려면 bindAsEventListener 함수를 사용할 수 있습니다. 이벤트 핸들러에서 인스턴스와 DOM 요소 모두에 액세스하려면 어떻게해야합니까? 유사
그렇지 가리킬 것이다 thisHow can I bind an event handler to an instance in JQuery?jquery 이벤트 처리기의 "this"바인딩 문제 (프로토 타입의 bindAsEventListener와 동일)

function Car(){ 
    this.km = 0; 
    $("#sprint").click(this.drive); //setup event handler 
} 

// event handler 
// in it I need to access both the clicked element 
// and the binding object (instance of car) 
Car.prototype.drive = function(){ 
    this.km += 10; // i'd like to access the binding (but jq changes it) 
    this.css({ // also the element 
     left: this.km 
    }); 
    // NOTE that is inside this function I want to access them not elsewhere 
} 

var car = new Car(); 

답변

0

에 (즉, 핸들러가 부착되는 소자)도 이벤트 객체의 속성 currentTarget에 전달된다. 당신이 바인딩 기능을 사용하는 경우 그래서, 당신은 이야기 : 당신은 여기

Car.prototype.drive = function(e) { 
    // this will be your car object 
    // e.currentTarget will be the element that you attached the click handler to 
} 
+0

나는'bindAsEventListener'을 사용할 수 없습니다. – clyfe

+0

@clyfe : 직접 작성하는 것이 매우 간단합니다. –

0

확인하다 : 나는 그것을 테스트하지 않았습니다 그러나 정직해야한다 또는 당신이 어디로 갔는지에 관해서는 잘못이 켜져

var car = {km:0}; 
$("#sprint").click(function(){ 
    car.km += 10; 
    $(this).css({ left: car.km }); 
}); 

당신의 "this"는 "자동차"객체가 아닌 "sprint"요소를보고 있습니다.

+0

이것은 내가 피하려고 노력하고있는 것입니다. – clyfe

+0

공정하게 :) 왜 먼 길을 가는지 궁금합니다. – Val

1

변수를 this에 바인드하고이를 사용하십시오.

function Car(){ 
    this.km = 0; 
    var that = this; 
    $("#sprint").click(function(){ 
     that.drive(this); 
    }); 
} 


Car.prototype.drive = function(element){ 
    this.km += 10; // i'd like to access the binding (but jq changes it) 
    this.css({ // also the element 
     left: this.km 
    }); 
    alert(element.innerHTML); 
    // NOTE that is inside this function I want to access them not elsewhere 
} 

핸들러 인스턴스

+0

전체 질문을 읽지 않았습니다. – clyfe

+0

그것 자체를 해결할 것이라고 생각 :)하지만 클래스 인스턴스와 요소 모두에 액세스하는 방법에 대한 답변을 업데이 트 –

+0

다른 질문도 이런 종류의 대답을 가지고 있지만 꽤 못생긴 찾습니다. 이것이 jquery 커뮤니티에서 이렇게하는 제안 된 방법입니까? 더 나은 무언가가 있어야합니다 ... 아니면 개인 취향의 문제 일뿐입니다. 나는이 로스트를 좀 더 내버려두고 아마도 당신의 대답을 받아 들일 것이다. – clyfe

관련 문제