2012-07-30 3 views
0

클래스 (모듈) (1) a Backbone.Collection var MessageCollection.prototype (2)으로 확장하려고합니다.다음 모듈을 어떻게 정의해야 작동합니까?

다음 모듈을 작동시키기 위해 어떻게 정의해야합니까?


(1)

/*global define, setTimeout*/ 
define([ 
    'underscore' 
], function (_) { 
    "use strict"; 

    return { 
     startPolling: function() { 
      this.polling = true; 
      this.executePolling(); 
//   _.bindAll(this, 'onFetch', 'startPolling', 'stopPolling'); 
     }, 

     stopPolling: function() { 
      this.polling = false; 
     }, 

     executePolling: function() { 
      this.fetch({success : this.onFetch}); 
     }, 

     onFetch: function() { 
      var self = this; 
      console.log(this); // undefined 
      console.log(self); // undefined 
      if (this.polling) { // Cannot read property 'polling' of undefined 
       setTimeout(this.executePolling, 1000 * 60 * this.minutes); 
      } 
     } 

    } 

    return Poll; 

}); 

(2)

/*global define*/ 
define([ 
    'underscore', 
    'backbone', 
    'moment', 
    '../utils/poller' 
], function (_, Backbone, Poller) { 
    'use strict'; 

    var MessageCollection = Backbone.Collection.extend({ 
     // some code 
    }); 

    _.extend(MessageCollection.prototype, Poller); 

    return MessageCollection; 
}); 

var messageCollection = new MessageCollection(); 
messageCollection. startPolling(); // Cannot read property 'polling' 
          // of undefined (see the comment on the code) 

답변

1

문제는 setTimeout 함께 할 수 있습니다. 함수가 setTimeout으로 전달되면 전역 범위에서 실행됩니다.

이렇게 전역 범위에서 this.executePolling이 호출됩니다. 즉, 해당 함수 안에 thiswindow이됩니다.

가로 변경합니다 : 당신의 응답을

var that = this; 
setTimeout(function(){ 
    that.executePolling 
}, 1000 * 60 * this.minutes); 
+0

감사하지만 잘하지, 내 질문에 자세한 내용을 추가했습니다. 잘하면 도움이 될 것입니다. 어쨌든 '속성을 읽을 수 없습니다'는 '정의되지 않음'의 폴링입니다. 이것은 창이 아니란 것을 의미합니다. –

+0

@LorraineBernard : 그것은 단지 생각이었습니다, 오 잘 = –

관련 문제