我应该如何定义以下模块才能使其正常工作

时间:2012-07-30 18:00:27

标签: javascript backbone.js

我试图用类(模块)(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 个答案:

答案 0 :(得分:1)

问题可能在于您的setTimeout。当函数传递给setTimeout时,它将在全局范围内执行。

因此,this.executePolling在全局范围内被调用,这意味着该函数内的this将为window

尝试将其更改为:

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