Node.js类递归发射

时间:2012-08-03 20:43:36

标签: javascript node.js timer

所以,我正在尝试使用Hands On Node.js上的Ticker,Event Emitter练习

我有这段代码:

var EventEmitter = require('events').EventEmitter,
    util = require('util');

// Ticker Constructor
var Ticker = function (interval) {
    this.interval = interval;
    this.pulse = null;
}

util.inherits(Ticker, EventEmitter);

Ticker.prototype.start = function() {
    this.emit('start');
    this.tick();
}

Ticker.prototype.stop = function() {
    if (this.pulse != null) clearTimeout(this.pulse);
    this.emit('stop');
}

Ticker.prototype.tick = function() {
    this.emit('tick');
    this.pulse = setTimeout(this.tick, this.interval);
}

var ticker = new Ticker(1000);
ticker.on('start', function() { console.log('Ticker: Start'); });
ticker.on('tick', function() { console.log('Ticker: Tick'); });
ticker.on('stop', function() { console.log('Ticker: Stop'); });

ticker.start();

运行时输出以下内容:

Ticker:开始 股票代码:勾选

timers.js:103
            if (!process.listeners('uncaughtException').length) throw e;
                                                                      ^
TypeError: Object #<Object> has no method 'emit'
    at Object.Ticker.tick [as _onTimeout] (/Users/twilson/Projects/tutorials/node/ticker-01.js:23:8)
    at Timer.list.ontimeout (timers.js:101:19)

ticker-01.js:23行的this.emit('tick');行{。}}。

帮助,因为我真的看不出地球上究竟出了什么问题,无疑会成为一个范围界定的事情? :(

1 个答案:

答案 0 :(得分:3)

调用setTimeout(this.tick, this.interval)时,tick方法将在默认上下文中执行,而不是this在那里引用的内容。你需要......

this的值绑定到自动收报器实例:

setTimeout(this.tick.bind(this), this.interval)

或保存对自动收报机实例的引用:

var self = this;
setTimeout(function() {
    self.tick();
}, this.interval);