我正在尝试使用其事件系统在 Nodejs 中进行开发。我已经实现了以下代码并且它通过了我的测试(使用 mocha)。that
但是,由于变量的范围,我不确定它是否可以在生产环境中工作。
在我的代码中,我分配that=this
. 之后我将config
对象分配给that.config
并且回调发出事件而不将配置作为参数传递。然后侦听器函数使用that.config
发出另一个信号。缓存对象是对 redis 数据库的请求。
问题是:that.config
当我发出信号时,对象是否总是引用范围,或者它是否可以在第一个发出的信号之后但在第一个侦听器使用之前that.config
(在另一个回调中)被另一个请求(获取另一个配置)修改?
function SensorTrigger(sensorClass, configClass) {
this.sensorClass = sensorClass || {'entityName': 'sensor'};
this.configClass = configClass || {'entityName': 'config'};
this.cache = new CacheRedis(app.redisClient, app.logmessage);
events.EventEmitter.call(this);
}
util.inherits(SensorTrigger, events.EventEmitter);
SensorTrigger.prototype.getSensorConfig = function(sensor, trigger) {
var that = this
, sensorKeyId = that.sensorClass.entityName + ':' + sensor
, baseKeyId = "base";
that.trigger = trigger;
that.id = sensor;
var callBack = function (config) {
config = utils.deepen(config);
that.receiver = config.receiver;
that.config = config.triggers[that.trigger];
that.emit(that.config.data, sensor);
}
that.cache.getItem(that.configClass, sensorKeyId, function(err, config) {
if (!config) {
that.cache.getItem(that.configClass, baseKeyId, function(err, config) {
callBack(config);
})
} else {
callBack(config);
}
})
}
SensorTrigger.prototype.getAllData = function(sensor) {
var that = this;
that.cache.getAllData(that.sensorClass, sensor, function(err, data) {
if (err) {
that.emit("error", err);
} else {
that.emit(that.config.aggregation, sensor, data);
}
})
}
trigger = new SensorTrigger();
trigger.on("onNewData", trigger.getSensorConfig);
trigger.on("all", trigger.getAllData);
配置对象的示例:
{
"id": "base",
"triggers.onNewData.data": "all",
"triggers.onNewData.aggregation": "max",
"triggers.onNewData.trigger": "threshold",
"receiver.host": "localhost",
"receiver.port": "8889",
"receiver.path": "/receiver"
}