I am trying to write a simple polling application using node.js. I want to write an EventEmitter that performs a timer action and emits events based on the result of this periodic action.
I start by creating my own object and inherit from EventEmitter. I start the timer using setInterval and set the method to call after the timer expires. In the timer callback method, I want to reference the variable of the object I created, but this
does not seem to refer to the object.
How can I refer to my variable in this method? Here is my code:
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;
source share