2012-06-11 2 views
0

간단한 날씨 위젯을 만들고 있습니다. 현재 기상 조건을 National Weather Service xml 파일에서 읽은 다음 모델에서 관련 데이터를 구문 분석하고 저장하려고하지만 $ .ajax에 대한 콜백이 연결되지 않습니다 (내가하는 방식).Backbone.Model 콜백 문제 및이

var Weather = Backbone.Model.extend({ 
     initialize: function(){ 
      _.bindAll(this, 'update', 'startLoop', 'stopLoop'); 
      this.startLoop(); 
     }, 
     startLoop: function(){ 
      this.update(); 
      this.interval = window.setInterval(_.bind(this.update, this), 1000 * 60 * 60); 
     }, 
     stopLoop: function(){ 
      this.interval = window.clearInterval(this.interval); 
     }, 
     store: function(data){ 
      this.set({ 
       icon : $(data).find('icon_url_name').text() 
      }); 
     }, 
     update: function(){ 
      $.ajax({ 
       type: 'GET', 
       url: 'xml/KROC.xml', 
       datatype: 'xml' 
      }) 
      .done(function(data) { 
       var that = this; 
       that.store($(data).find('current_observation')[ 0 ]); 
      }); 
     } 
    }); 
    var weather = new Weather(); 

데이터가 올바르게 읽혀 지지만 콜백의 완료 기능을 통해 저장소 기능을 호출 할 수 없습니다. .. 단지 구문 분석하고 "this.set"을 할 것 "완료"경우 (나는 행복 할 것이다 당신의 도움에 미리

감사

답변

4

나는 당신이 당신의 var that = this; 한 수준 위로 이동할 필요가 있다고 생각 :

update: function(){ 
    var that = this; // <-------------- You want this 'this' 
    $.ajax({ 
     type: 'GET', 
     url: 'xml/KROC.xml', 
     datatype: 'xml' 
    }) 
    .done(function(data) { // <----- rather than the 'this' in here 
     that.store($(data).find('current_observation')[ 0 ]); 
    }); 
} 

당신은 당신의 done가 호출되는 시점에서, 당신의 update 방법에 this의 현재 값을 캡처하려면, 너무 늦게 done 콜백이 이미 잘못된 this있을 것이다으로 될 것입니다.

+1

대안 :'.done (_. bind (function() {...}, this))' – Yaroslav

+0

그게 문제였습니다. 고맙습니다. –

+2

가장 유용한 명명 규칙은 외부 범위에서'var _this = this;'입니다. –

1

위의 대답은 효과가 있지만 밑줄이있는 기본 제공 기능이 있습니다. 이 시도 :

.done(_.bind(function(data) { // <----- rather than the 'this' in here 
    this.store($(data).find('current_observation')[ 0 ]); 
}, this)); 

이 방법은 _.bindthis에 실행 컨텍스트를 설정, 당신은 that=this을 할 필요가 없을거야.

또한, _.bindAll(this, ...)this에 바인딩한다는 것을 보장하지 않습니다. 레벨에서 _.bind을 사용하면 항상 작동해야합니다.