我有一个节点js脚本:
var EventEmitter = require('events').EventEmitter,
util = require('util');
var pfioObject = function () {
this.init = function () {
console.log("started server");
};
this.deinit = function () {
console.log("stopped server");
};
this.read_input = function () {
return 0;
};
};
console.log(util.inspect(EventEmitter, false, null)); //<--- this shows no method emit either
var pfio = new pfioObject();
var pfioServer = function () {
this.prev_state = 0;
this.start = function () {
pfio.init();
this.watchInputs();
};
this.stop = function () {
pfio.deinit();
};
}
util.inherits(pfioServer, EventEmitter);
// add some event emitting methods to it
pfioServer.prototype.watchInputs = function () {
var state = pfio.read_input();
if (state !== this.prev_state) {
this.emit('pfio.inputs.changed', state, this.prev_state);
this.prev_state = state;
}
setTimeout(this.watchInputs, 10); // going to put this on the event loop next event, more efficient
};
// export the object as a module
module.exports = new pfioServer();由于某些原因,节点错误说没有像emit这样的对象,我已经做了npm install events,看看它是否会修复它,它没有。我不知道为什么我会得到这个错误。
我认为在我的代码中有一个错误,但我什么也看不见。
要运行这段代码,我有另一个脚本,它执行以下操作:
var pfioServer = require('./pfioServer'),
util = require('util');
console.log(util.inspect(pfioServer, false, null)); //<--- this line shows the pfioServer with out the prototype function watchInputs
pfioServer.start();编辑
我想我可能错过了一些关于事件发射器内容的重要代码,我正在研究事件发射器类的实例化。
微小变化
因此,我没有继承EventEmitter,而是通过执行var emitter = new EventEmitter()实例化它。
然后,我在util.inspect中得到了关于对象必须是对象或为null的错误。
还没有成功。
发布于 2014-02-04 19:02:32
发布于 2014-02-04 19:00:54
原因是这一行:
setTimeout(this.watchInputs, 10);当触发超时并调用this.watchInputs时,它已经失去了上下文。
您需要通过使用this来显式地设置该调用的上下文对象(换句话说,方法中的bind应该指向什么)
setTimeout(this.watchInputs.bind(this), 10);发布于 2014-02-04 19:03:58
console.log(util.inspect(EventEmitter,false,null));//这表明没有任何方法发出
EventEmitter构造函数没有这样的方法。EventEmitter.prototype有。要打印(非枚举) .prototype属性,可以使用util.inspect(EventEmitter, {showHidden: true})作为注释中提到的@Emissary。
//这一行显示了带有prototype函数pfioServer的watchInputs console.log(util.inspect(pfioServer,false,null));
是。util.inspect不显示继承的属性,只显示在pfioServer实例本身上明显的属性。
setTimeout(this.watchInputs,10);//将其放在事件循环下一个事件中,效率更高
我宁愿说它可以防止无限循环…但是,这也会破坏下一个调用中的this上下文,后者不再是您的pfioServer实例。请参阅回调内部的上下文?
然而,在您的情况下,我不认为使用构造函数和从原型继承的必要性。您只是导出一个单例对象,您只需用一个对象文本实例化它的变量名并引用它。
https://stackoverflow.com/questions/21559771
复制相似问题