2014-04-17 4 views
2

저는 현재 약속에 어려움을 겪고 있으며 개념이 조금 잘못되었다고 생각합니다. 기본적으로 내가하려는 것은 작은 템플릿 핸들러를 작성하는 것입니다.다른 방법으로 약속을 기다리는 중

템플릿을로드하여 속성에 저장하고 chainable이 될 load() 메서드가 있습니다. 내가 연결하고자하는 메소드는 attachTo()이며 이전에로드 한 템플릿을 DOM 요소에 추가합니다.

템플릿이 비동기 적으로로드되기 때문에 약속을 사용하려고했습니다. 그러나 약속에 대한 done() 메서드가 즉시 시작되고 비동기 호출이 완료되기 전에 발생합니다.

나는 그런 식으로 전화 :

tpl.load('stuff.html').attachTo($('.someElement'));

나는 그것이 내가 attachTo()를 호출 할 때마다, 그것은 비동기 물건을 끝낼 얻을 내 이전이라고 load() 메서드 기다리는 것을 행동 할 무엇, done 메서드에서 제공된 콜백을 시작합니다.

여기 그것이 범위 지정 문제라고 밝혀졌다

var tpl = { 
... 
    template: null, 
    promise: null, 

    load: function(template) { 
     this.promise = $.get(this.templateUrl + template, function(response){ 
      this.template = response; 
      console.log(this.template); 
      //Outputs the desired value 
     }); 
     return this; 
    }, 

    attachTo: function(el) { 
     var self = this; 
     $.when(this.promise).done(function(){ 
      //outputs null but should output the 
      //value that has been set in my async call 
      console.log(self.template); 
     }); 
    } 

.. 
} 

tpl.load('stuff.html').attachTo($('.someElement')); 
+2

, 어쩌면 당신이 (결과에 관계없이 유형의 호출 완료) 오류를 받고 있습니다. 나쁜 요청으로부터 좋은 요청 결과를 구별하기 위해 this.promise.then(). fail() 접근 방식을 시도해보십시오. –

+0

감사합니다. @PeterAronZentai. 정말로 내 실수 였어. 템플릿 속성을 설정하면 범위가 엉망이됩니다. 이것은 더 이상 내 객체를 참조하지 않고 대신 콜백의 범위를 참조합니다. 그냥 프록시를 사용해야했습니다. 그 문제를 지적 해 주셔서 감사합니다! – thpl

+0

나는 당신의 코드에 어떤 문제가 있는지 모르겠다. –

답변

1

문제를 이미 확인했지만 제안 된 해결책은 좋지 않습니다.

당신은 변화를 전파하기위한 약속을 somewhen 설정하고 사용하는 전역 변수를 사용하지 말아야하지만, 약속은 다음 값을 표시한다. 이것은 더 나은 기능적 프로그래밍 스타일로 이어집니다. 귀하의 경우에는

:

이 그냥 OK 보이는
var tpl = { 
    … 
    templatePromise: null, 
    load: function(template) { 
     this.templatePromise = $.get(this.templateUrl + template).then(function(response) { 
      console.log(this.template); 
      //Outputs the desired value 
      return response; 
     }); 
     return this; 
    }, 
    attachTo: function(el) { 
     $.when(this.templatePromise).done(function(template) { 
      // get the template here:    ^^^^^^^^ 
      console.log(template); 
     }); 
    } 
    … 
} 
1

핸들러의 관련 부분입니다. 지연에 대해서는 아무런 문제가 없었지만 인스턴스의 범위에 값을 할당했습니다.

load: function(template) { 
    this.promise = $.get(this.templateUrl + template, function(response){ 
     this.template = response; 
     console.log(this.template); 
     //Outputs the desired value 
    }); 
    return this; 
}, 

여기서 this.template에 값을 할당했습니다. 그러나 나는 내 물건의 범위에 있지 않았지만 $.get() 방법의 폐쇄의 범위에 있었다. 따라서 다른 방법은 결코 거기에 저장되지 않았기 때문에 속성에서 가치를 끌어낼 수 없습니다. 내가 처음 대신 this를 사용하는 폐쇄 내부 그것에 self 변수에 개체 인스턴스의 인스턴스를 할당 대해 참조

load: function(template) { 
    var self = this; 
    this.promise = $.get(this.templateUrl + template, function(response){ 
     self.template = response; 
    }); 
    return this; 
}, 

:

내가 함께했다. 그것을 더 우아하게 해결하기 위해서도 $.proxy()을 사용할 수있었습니다.

그게 전부입니다. 그것은 단지 범위 지정 및 지연된 이슈가 아닙니다.