Sunday 19 March 2017

How to invoke EventEmitter's inherited function in another module?

//player.js

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

module.exports = Player;

function Player(uid, emailAddress, password) {
   this.uid = uid;
   this.emailAddress = emailAddress;
   this.password = password;

   EventEmitter.call(this);
}

inherits(Player, EventEmitter);

// auth.js
var Player = require('./player');
var p = new Player(1000, 'someone@example.com', '12345');

// Here crashed
p.on('event', function() {
   console.log('Event emitted!);
});
p.emit('event');

I am new to Node.JS programming. I am trying to understand Node's EventEmitter module. However, when EventEmitter's on(event, callback) function is invoked in auth.js, it throws that error

TypeError: p.on is not a function
    at Object.<anonymous> (/home/someone/App/libs/auth.js:7:3)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:425:7)
    at startup (bootstrap_node.js:146:9)
    at bootstrap_node.js:540:3

I have no idea why it happens. How can I resolve this problem?



via Rinzler

No comments:

Post a Comment