怎么了?
附注: 我是 node.js 的新手,我来自 .Net 世界!
我的 server.js 代码:
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!!!!!!!!!!');
});
和这个控制台输出:
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
最佳答案
您忘记从您的 v
函数返回事件发射器:
var v = function() {
var e = new events();
e.emit('start');
return e;
};
另请注意,start
事件将不会被调用,因为您在订阅它之前已经发出了该事件。所以你可以稍微修改一下你的代码:
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');
关于javascript - Node.js 无法读取未定义的属性 'on',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35116729/