所以,我正在尝试 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();
运行时输出以下内容:
代码:开始 代码:勾选
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');
。Ticker.prototype.tick
帮助,因为我真的看不出到底出了什么问题,毫无疑问,这肯定是一个范围界定的事情?:(