2012-07-30 34 views
0

我试图扩展一个类(模块)(1)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,这意味着该函数内部的this将是window

尝试将其更改为:

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

感谢您的答复,但是这是不对的,我增加了更多的细节,我的问题。希望这会有所帮助。无论如何'不能读取未定义的属性'轮询',这意味着这不是窗口。 – 2012-07-30 19:14:56

+0

@LorraineBernard:这只是一个想法,哦很好= / – 2012-07-30 19:18:28

相关问题