我正在编写nodejs模块并尝试将事件发射器绑定到“scrappy.get”。似乎我只能将它绑定到“垃圾”....所以“scrappy.get(key).on('complete'....”不起作用。
如何将事件发送到子对象'get'?
我的NodeJS模块:
var util = require('util'),
EventEmitter = require('events').EventEmitter;
function Scrappy(id) {
}
util.inherits(Scrappy, EventEmitter);
Scrappy.prototype.get = function (key) {
var self = this;
self.emit('complete', "here");
**return this;**
}
module.exports = Scrappy;
我的NodeJS应用代码:
var Scrappy = require('./scrappy.js')
var scrappy = new Scrappy("1234");
scrappy.get("name").on('complete', function(data){
console.log("secondary");
});
结果:
scrappy.get("name").on('complete', function(data){
^
TypeError: Cannot call method 'on' of undefined
编辑:已解决。添加“return this;”为我解决了。谢谢!
答案 0 :(得分:1)
问题是您的this
不同,因为您处于不同的功能中。您需要将Scrappy实例this
捕获到变量并改为访问它:
Scrappy.prototype.get = function (key) {
var self = this;
redisclient.get(key, function(err, reply) {
self.emit('complete', reply);
});
};
此外,不是手动改变原型__proto__
等,通常是节点核心使用的(以及许多模块开发人员使用的)是内置的util.inherits()
。另外一点是你没有从get()
返回实例。以下是这些变化的示例:
var util = require('util'),
EventEmitter = require('events').EventEmitter;
function Scrappy(id) {
}
util.inherits(Scrappy, EventEmitter);
Scrappy.prototype.sendToEngine = function(message) {
};
Scrappy.prototype.set = function(key, value) {
};
Scrappy.prototype.get = function(key) {
var self = this;
redisclient.get(key, function(err, reply) {
self.emit('complete', reply);
});
return this;
};
module.exports = Scrappy;