Mil*_*lad 6 javascript events node.js dom-events
怎么了?
ps:我是来自.Net世界的node.js和我的新手!
我的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!!!!!!!!!!');
});
Run Code Online (Sandbox Code Playgroud)
并且这个控制台输出:
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
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 11
您忘记从v函数返回事件发射器:
var v = function() {
var e = new events();
e.emit('start');
return e;
};
Run Code Online (Sandbox Code Playgroud)
另请注意,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');
Run Code Online (Sandbox Code Playgroud)