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)
4

1 回答 1

1

问题可能出在您的setTimeout. 当一个函数被传递给 时setTimeout,它会在全局范围内执行。

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

尝试将其更改为:

var that = this;
setTimeout(function(){
    that.executePolling
}, 1000 * 60 * this.minutes);
于 2012-07-30T18:05:13.903 回答