0
func parent(children){
    for(var i =0;i<children.length;i++){
       this.children[i] = new Child(fname, lname);
    }
 this.printNames = function(){
          for(var i =0;i<this.children.length;i++){
      console.log(this.children[i].fname);
    }
  }
}
func child(fname,lname){
 this.fname = fname;
 this.lname = lname;
 this.changefname = function(_fname){
 this.fname = _fname;
 this.emit('NameChanged');
 }
}

How do I do something like,

parentObj.children.on("NameChanged", parentObj.printNames);

I want to listen to a event emitted by a child Obj in the children collection and call a function in the parent Object.

Rajiv Prathapan
  • 75
  • 1
  • 10

1 Answers1

0

It's not too complicated, when you want an object to emit an event, you need to give the object the value of events.EventEmitter, when you do that, it can not hold a string or a number but an event.

Example code when working with objects

var events = require('events');

var example_emitter = new events.EventEmitter;

var myObj = {};

//Basic index of an object

myObj['someevent'] = new events.EventEmitter;

myObj['someevent'].on("somemessage", function(message){
  console.log(message);
})

myObj['someevent'].emit("somemessage", "this is some message");

//Getting to more low level

myObj['element'] = {};
myObj['element']['secondevent'] = new events.EventEmitter;

myObj['element']['secondevent'].on("anotherMessage", function(message){
  console.log('the length of the message is ' + message.length + ' the message is ' + message);
})

myObj['element']['secondevent'].emit("anotherMessage", 'hello there');

Here is some example code for working with arrays. To elaborate on what I've told above, I have give someArray some values, which are being 1, 2 and 3, when I set those three indexes to an Event object inside a for loop, their values are overridden, so they become an event object, and when you log them, they will not print 1,2, 3 but eventObj,eventObj,eventObj.

//Working with arrays

var someArray[1, 2, 3];

for(var i = 0; i < someArray.length; i++){
  someArray[i] = new events.EventEmitter;        //changing the values
  someArray[i].on('printTheIndex', function(){
    console.log(someArray[i]);
  });

  someArray[i].emit('printTheIndex'); // the indexes are now event objects, they will not log 1,2,3 but objects of events
}

So in order for an element to act like an event listener you need to first convert its value to an event object by creating a new events.EventEmitter

Ahmed Can Unbay
  • 2,694
  • 2
  • 16
  • 33