What is wrong?
p.s. : I am new to node.js and I'm from .Net world!
My server.js code :
var events = require('events').EventEmitter;
var v = function() {
var e = new events();
e.emit('start');
};
var r = v();
r.on('start', function(){
console.log('event start just fired!!!!!!!!!!');
});
and this console output :
TypeError: Cannot read property 'on' of undefined
at Object.<anonymous> (E:\Project\node\BasicSocial\server.js:12:2)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:442:10)
at startup (node.js:136:18)
at node.js:966:3
To solve the "Cannot read properties of undefined" error, make sure that the DOM element you are accessing exists. The error is often thrown when trying to access a property at a non-existent index after using the getElementsByClassName() method.
The "Cannot set properties of undefined" error occurs when setting a property on an undefined value. To solve the error, conditionally check if the value is of the expected type (object or array) or has to be initialized before setting the property on it.
A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .
To solve the "Cannot read property 'value' of null" error, make sure you aren't accessing the value property on a null value, e.g. a non-existent DOM element. An element with the provided id does not exist in the DOM, so the getElementById method returns null .
You forgot to return the event emitter from your v
function:
var v = function() {
var e = new events();
e.emit('start');
return e;
};
Also notice that the start
event will not be called because you have emitted the event before you subscribed to it. So you could kind of rework your code a little:
var events = require('events').EventEmitter;
var v = function() {
var e = new events();
return e;
};
var r = v();
r.on('start', function(){
console.log('event start just fired!!!!!!!!!!');
});
// emit the event after you have subscribed to the start callback
r.emit('start');
r
is undefined, since v
isn't returning anything. That's why you're getting the error. And even if you return the event, your code won't give you the desired output, since you need to use on("start")
before you use emit("start")
var events = require('events').EventEmitter;
var e = new events();
e.emit('start'); //This won't trigger the console.log
//Need to be binded before you emit the event.
e.on('start', function(){
console.log('event start just fired!!!!!!!!!!');
});
e.emit('start'); //This will trigger the console.log
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With