Node JS event not firing
I am trying to create an event fire in my node JS code but cannot figure out why it is not.
I have a module like this:
var zookeeper = require('node-zookeeper-client'),
events = require('events'),
util = require('util');
var client;
var KafkaZookeeperMonitor = function(){
events.EventEmitter.call(this);
}
util.inherits(KafkaZookeeperMonitor, events.EventEmitter);
KafkaZookeeperMonitor.prototype.connectToZk = function(zookeepers){
client = zookeeper.createClient(zookeepers);
client.connect();
client.once('connected', function () {
console.log('Connected to ZooKeeper');
this.emit('connected');
});
}
module.exports = KafkaZookeeperMonitor;
and I am calling it from my index.js file like this:
var KafkaZookeeperMonitor = require('./kafkaZookeeperMonitor'),
kafkaStatus = new KafkaZookeeperMonitor(),
brokerPath = '/brokers/ids';
kafkaStatus.connectToZk('192.168.50.252:2181');
kafkaStatus.once('connected', function(){
console.log('watcher connected to Zookeeper');
})
When I run the code, I get a log message
'Connected to Zookeeper'
but this.emit('connected');
doesn't seem to work.
I have looked online and I think I am setting my event emitter correctly. Can anyone help me where I may have gone wrong here?
thank
source to share
The callback function context is not KafkaZookeeperMonitorz
Object, so this
it is not an object instance.
This should work:
KafkaZookeeperMonitor.prototype.connectToZk = function(zookeepers){
var self = this;
client = zookeeper.createClient(zookeepers);
client.connect();
client.once('connected', function () {
console.log('Connected to ZooKeeper');
self.emit('connected');
});
}
The reason it is not throwing an error may be due to something that client
also spreadsEventEmitter
source to share
I don't believe 'this' is what you think it is ...
this.emit('connected');
Debug and make sure your 'this' is what you are looking for ...
http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/
source to share