I am trying to write a simple polling application using NodeJS. I’m wanting to write an EventEmitter that performs an action on a timer and emits events based on the result of that periodic action.
I’m starting by creating my own object and inheriting from EventEmitter. I kick off a timer using setInterval, and specify the method to call after the timer elapses. Within the timer callback method, I want to reference a variable of the object that I’ve created, but this does not appear to refer to the object.
How can I reference 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);
});
};
// inherit from event emitter
util.inherits(JobPoller, events.EventEmitter);
// export the poller instance
module.exports = new JobPoller;
this.checkis just a simple function, the value ofthisinside that function will be determined when the function is called.Node should support
bindso you can bind the function to your desiredthislike this:Alternatively, you can use a closure to manually force
thisto be what you want: