2011-07-03 5 views
3

이 아약스 호출이 클래스가 있습니다 :Jquery ajax : 설정 범위 전달

 this.__type = "PersonDto:#Empower.Service.Common.Dto"; 
    this.Name = undefined; 
    this.Surname = undefined; 

    this.GetById = function (id) { 
     return $.ajax({ 
      type: "POST", 
      url: "/Services/PersonService.svc/GetPersonById", 
      data: JSON.stringify(id), 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function (data) { 
       ... 
       this = data; 
       ... 
      } 
     }); 
    } 
}; 
 this.__type = "PersonDto:#Empower.Service.Common.Dto"; 
    this.Name = undefined; 
    this.Surname = undefined; 

    this.GetById = function (id) { 
     return $.ajax({ 
      type: "POST", 
      url: "/Services/PersonService.svc/GetPersonById", 
      data: JSON.stringify(id), 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function (data) { 
       ... 
       this = data; 
       ... 
      } 
     }); 
    } 
}; 

아약스 호출의 성공 나는 사람의 현재 인스턴스를 설정하려면하지만 "이" 설정 범위가 정확하지 않습니다. 전역 변수를 사용하는 것보다 더 우아한 방법이 있습니까?

미리 도움을 주셔서 감사합니다. 나쁜 영어로 사과드립니다.

+0

스코프 문제에도 불구하고, 당신은 덮어 쓸 수 없습니다'this' – Alnitak

답변

5

jQuery.ajax()[docs] 방법은 당신이 콜백에서 this의 값을 설정할 수 context 속성을 제공에서 그 변수를 사용할 수 있습니다.

그냥 수행

context: this, 

... 당신의 전화에, 같이 :

this.GetById = function (id) { 
    return $.ajax({ 
     type: "POST", 
     context: this, // <---- context property to set "this" in the callbacks 
     url: "/Services/PersonService.svc/GetPersonById", 
     data: JSON.stringify(id), 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function (data) { 

      // in here, "this" will be the same as in your "getById" method 

     } 
    }); 
} 
1

당신은 세계가 필요하지 않습니다 죄송합니다.

은 그냥 넣어 :

var self = this; 

바로 return $.ajax(...) 라인 이전, 다음, AJAX 콜백 함수 내에서 현재 인스턴스를 참조하는 self를 사용합니다.

이 변수는 GetById() 기능 안에서만 사용할 수 있습니다.

0

물론, 당신은 변수에 this를 넣고 콜백

var self = this; 

this.GetById = function (id) { 
    return $.ajax({ 
     type: "POST", 
     url: "/Services/PersonService.svc/GetPersonById", 
     data: JSON.stringify(id), 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function (data) { 
      ... 
      self = data; 
      ... 
     } 
    }); 
} 
+1

아니, '자기 = 데이터 ", 아마, 그 자체로 이전 값을 덮어 씁니다. 'self.something = data' 또는'self.something (data);와 유사합니다. – Pointy

+0

사실,'self'를 덮어 쓰는 것은 어떤 메소드도 붙이지 않은 평범한 객체로 끝날 것이고, 어쨌든'this'를 바꾸지 않을 것입니다. – Alnitak

+0

사실 당신들 말이 맞습니다. 이 경우 나는 데이터가 메소드없이 이것과 같을 것이라고 생각했다. Pointy는 적절한 해결책이 될 것이라고 말했다. 그런 다음 어떤 콜백 함수 매개 변수 데이터가 문제의 해결 방법을 제공하는지 알아야합니다. – Tx3