我正在尝试使用node.js编写一个简单的轮询应用程序.我想编写一个EventEmitter,它对计时器执行操作,并根据该周期性操作的结果发出事件.
我首先创建自己的对象并继承自EventEmitter.我使用setInterval启动计时器,并在计时器结束后指定要调用的方法.在计时器回调方法中,我想引用我创建的对象的变量,但这似乎并不引用该对象.
var util = require('util'),events = require('events'),timers = require('timers'),redis = require('redis'); // define worker object var JobPoller = function () { // inherit event emitter events.EventEmitter.call(this); // save reference to database this.db = redis.createClient(); // start main loop this.interval_id = timers.setTimeout(this.check,1000); }; JobPoller.prototype.check = function () { // pop a job off the queue if possible this.db.rpop('pdf-job-queue',function (err,result) { if (err != null) this.emit('error',err); if (result != null) this.emit('job',JSON.parse(result)); // check for more jobs this.interval_id = timers.setTimeout(this.check,1000); }); }; // inhert from event emitter util.inherits(JobPoller,events.EventEmitter); // export the poller instance module.exports = new JobPoller;