-1

Main File

var DogModule = require('Dog');
var dogsList = [];

function addNewDog(){
  var newDog = new Dog();
  dogsList.push(newDog);
}

???.on('bark', function(barkSound) {
    console.log(barkSound);
});

Dog File

var EventEmitter = require('events').EventEmitter;

function Dog() {

    EventEmitter.call(this);

    this.name = "asda";
    this.chipId = 1234;

    this.emit('bark', "au-au");
}

Dog.prototype = {

   getName: function () {
     return this.name;
   },

   getChipId: function () {
     return this.chipId;
   }
}

Question 1 - How can i properly add EventEmitter.prototype to Dog object and save the current prototype and basically just get access to EventEmitter methods?

  • Dog.prototype = Object.create(EventEmitter.prototype);
  • Using util module and then util.inherits(Dog, EventEmitter);

The problem here is just how to not overwrite the existing methods...


Question 2 - Handle one object its no problem but for multiple how i can handle them individuality, knowing that they will be stored on that list?

Thank you.

Xplouder
  • 148
  • 1
  • 4
  • 13
  • 1
    For inheriting, follow the standard Node docs on extending EventEmitter: https://nodejs.org/api/events.html#events_inheriting_from_eventemitter – TbWill4321 Dec 22 '15 at 20:18
  • As i said above the problem is that using util.inherits(Dog, EventEmitter) (as on documentation) overwrite the existing methods of Object prototype. – Xplouder Dec 22 '15 at 20:24
  • 1
    You put the ` util.inherits(Dog, EventEmitter)` first and then you add each method individually as in `Dog.prototype.getName = function() {}` so you don't overwrite the previous prototype. Doing this `Dog.prototype = {...}` overwrites any previous `Dog.prototype`, so don't do that. – jfriend00 Dec 22 '15 at 20:27
  • Tbh i knew that, but its kinda painful to reformat the entire prototype when the object have about 100 methods. Thats why i asked hoping a more efficient solution. – Xplouder Dec 22 '15 at 20:32
  • You can merge an object full of methods with the prototype. – jfriend00 Dec 22 '15 at 20:53

1 Answers1

1

To prevent rewriting the prototype, you can use Object.assign:

util.inherits(Dog, EventEmitter);
Dog.prototype = Object.assign({
  getName: function () {
    return this.name;
  },
  getChipId: function () {
    return this.chipId;
  }
}, Dog.prototype);
TbWill4321
  • 8,626
  • 3
  • 27
  • 25
  • Great find, its part of ES6 new features! Btw any idea about the question 2? The first was more curiosity :p – Xplouder Dec 22 '15 at 20:58