4

I am trying to make an event fire in my node JS code but cannot work out why it isn't.

I have a module as follows:

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 call this from my index.js file as follows:

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 the log message

'Connected to Zookeeper'

but the this.emit('connected'); does not seem to fire.

I've looked around on the web and I think I'm setting up my event emitter correctly. Can anybody help me out where I might be going wrong here?

Thanks

Jon Hunter
  • 882
  • 2
  • 8
  • 18

2 Answers2

3

The context of the callback function is not the KafkaZookeeperMonitorz Object so this is not really the 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's not throwing an error may be because the client is also extending EventEmitter

Maroshii
  • 3,937
  • 4
  • 23
  • 29
1

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/

Xogle
  • 363
  • 3
  • 16