2014-09-09 2 views
0

jquery 이벤트 처리기에서 프로토 타입 메서드를 호출하려고합니다. 다른 메서드에서 프로토 타입 메서드 호출

$('#' + this.ID + ' .selMake').on('change', this.getCarModel()); 

내가 말하는 오류를 얻을 : catch되지 않은 형식 오류 : 개체 [글로벌 오브젝트] 어떤 방법이 'getCarModel'

내가 잘못 여기서 뭐하지하고있다이 같은 코드가?

+3

'이'란 무엇입니까? – tymeJV

+0

@wootscootinboogie 아니요, 코드가 콜백 함수에 없으므로 아닙니다. – Barmar

+1

관련 : http://stackoverflow.com/questions/24173440/save-access-to-this-scope –

답변

0

사용이 코드 : 당신은 그냥 사용할 수없는 이유를 들어

vehicleSelect.prototype.getCarMakes = function() { 
    // Optional parameters 
    var options = {}; 

    var select = $('#' + this.ID + ' .selMake'), 
     that = this; 

    select.on('change', function(e) { 
    that.getCarModel(); 
    }); 

    // Callback function to be called when the API response is returned 
    function success(res) { 
    for (var i=0; i<res.makes.length; i++) { 
     $("<option>",{ 
     value: res.makes[i].niceName, 
     html: res.makes[i].name 
     }).appendTo(select); 
    } 
    select.removeAttr("disabled"); 
    select + $(' option[value="placeholder"]').html('Select Make'); 
    } 
    // Oops, we have a problem! 
    function fail(data) { console.log(data); } 
    // Fire the API call 
    this.res.api('/api/vehicle/v2/makes', options, success, fail); 
}; 

select.on('change', this.getCarModel) (또한 다른 솔루션을 제공하는) this question를 참조하십시오.

+0

니스! 이 작품! – user3312508

1

먼저해야 할 일은 함수에서 괄호를 제거하는 것입니다. 현재 코드에서 기대하는 것은 getCarModel이 이벤트가 트리거 될 때 호출되는 함수를 반환하는 것입니다. 아니이

$('#' + this.ID + ' .selMake').on('change', that.getCarModel); 

을 :

$('#' + this.ID + ' .selMake').on('change', that.getCarModel()); 

은 다음 당신이 그런 식으로 함수를 호출 할 경우, 당신이 할 수있는 : 그것은 다음과 같습니다

은 당신이하고 싶은 것입니다

var that = this; 
$('#' + this.ID + ' .selMake').on('change', function() { 
    that.getCarModel(); 
}); 

위의 경우 익명 함수를 인수로 전달하여 내부 코드를 실행합니다.

위의 함수에서 this의 정의는 이벤트를 트리거 한 요소에 따라 달라집니다. 당신이 당신의 this 객체에 연결되는 this의 정의를 원하는 경우, 다음을 수행 할 수 있습니다

var that; 
$('#' + this.ID + ' .selMake').on('change', that.getCarModel); // This will execute the function this.getcarModel 

당신은 또한 사용할 수 있습니다 :

가장 간단하고 이해 방법은 that 변수를 사용하는 것입니다 bind 브라우저에서 ES5를 지원합니다.

$('#' + this.ID + ' .selMake').on('change', this.getCarModel.bind(this)); 
+2

하지만 그건 정의되지 않았습니다 ... –

+0

당신 말이 맞아요. 결정된. –

1

.on()에 두 번째 인수는 함수이어야한다. 이벤트가 발생할 때가 아니라 핸들러를 바인딩 할 때 함수를 호출하고 있습니다. 그것은해야한다 :

var self = this; 
$('#' + this.ID + " .selMake').on('change', function() { 
    self.getCarModel(); 
}); 

당신은 너무 this가 폐쇄에 저장됩니다 로컬 변수 self을 사용해야합니다. 이에 대한 자세한 내용은

"this" keyword in event methods when using JavaScript prototype object

를 참조하십시오.

관련 문제