2014-11-17 3 views
1

저는 현재 작은 Javascript 객체를 작성하고 있습니다.이 객체는 클릭 리스너를 특정 요소에 추가하여 PHP 함수에 대한 AJAX 호출을 트리거합니다. 이 모든 것은 잘 동작하지만 AJAX가 응답 할 때 함수를 호출하려고합니다. 응답을 받으면 트리거 될 AJAX 호출에 함수를 전달하여이 작업을 수행했습니다.자바 스크립트 객체 프로토 타입이 범위를 벗어났습니다

내가 겪고있는 문제는 protoytype을 호출 할 때 (AJAX 호출에서 발생할 수있는 aynschronous 문제를 막기 위해) 객체의 범위를 잃어 버리고 있다는 것입니다. 'this'객체 (또는 self)는 창에 설정되고 내가 만든 객체의 인스턴스로 설정되지 않습니다. 당신이 볼 수 있듯이

//Rating Submit 
var Rater = function(element, videoId, ratingStars, userId) { 
    this.userId = userId, 
    this.element = element; 
    this.videoId = videoId; 
    this.ratingStars = ratingStars; 
    var self = this; 

    jQuery(this.ratingStars).click(function(e) { 
     e.preventDefault(); 
     self.ratingClick(this, self.changeStar); 
    }); 
} 

Rater.prototype.ratingClick = function(item, changeStar) { 
    jQuery.ajax({ 
     type  : 'post', 
     dataType : 'json', 
     url  : 'api/rate-video', 
     data  : "userId=" + this.userId + "&videoId=" + this.videoId + "&rating=" + jQuery(item).attr("data-score"), 
     success : function(data) { 
      changeStar(data, item);  
     } 
    }); 
} 

Rater.prototype.changeStar = function(response, item) { 
    var maxCount = jQuery(item).attr("data-score"); 
    //console.log(self); 
    jQuery(self.ratingStars).each(function(key, value) { 
     alert(key); 
    }); 
} 

, 내가 응답이 주어 졌을 때 호출되는이에 대한 AJAX 호출에 'self.changestar'프로토 타입 기능을 전달하고있다 : 여기 내 코드입니다. 내가 특정 인스턴스에 대한 생성자에서 설정 한 변수에 액세스하려고 시도하면 Window 객체이며 클래스의 인스턴스가 아니라고 표시됩니다. 인스턴스 내에서 콜백으로 프로토 타입 함수를 전달할 수 있습니까? 나는 .... 내가 자신을 좋아 설명했다

감사

희망

답변

3

문제는 당신이 수행 할 때이다 :

self.ratingClick(this, self.changeStar); 

를 당신이 jQuery를 클릭으로 Rating 정확하게 같은 문제가 콜백 : self 변수로 해결 : 함수 참조 changeStar 만 전달되고 this으로 사용할 값은 아무 것도 전달되지 않습니다.

하나의 솔루션이라고 할 때, 특정 this 값 (및 선택적 인수)와 함께 원본을 호출 다른 기능을 다시 얻기 위해 당신이 함수에 호출 Function#bind을 사용하는 것입니다

self.ratingClick(this, self.changeStar.bind(self)); 

대안 성공 처리기에서 Function#call을 사용하여 다음

self.ratingClick(this, self.changeStar, self); 

을 ... 그리고 :

,369을 별도로 this로 사용할 값을 전달할 수
Rater.prototype.ratingClick = function(item, changeStar, thisArg) { // <== Change here 
    jQuery.ajax({ 
     type  : 'post', 
     dataType : 'json', 
     url  : 'api/rate-video', 
     data  : "userId=" + this.userId + "&videoId=" + this.videoId + "&rating=" + jQuery(item).attr("data-score"), 
     success : function(data) { 
      changeStar.call(thisArg, data, item);     // <=== And here 
     } 
    }); 
} 
+1

브릴리언트. 큰 설명도. 감사 – devoncrazylegs

관련 문제