0

我正在尝试使用其事件系统在 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"
}
4

1 回答 1

0

仅当它下次运行时“那个”被更改为this. 由于每个实例都有自己的功能,因此可能发生的唯一方法是您执行以下操作:

var trigger = new SensorTrigger(sensor, config);
trigger.getSensorConfig.apply(SOMETHING_ELSE, sensor2, trigger2);

只要您像往常一样使用它:

var trigger = new SensorTrigger(sensor, config);
trigger.getSensorConfig(sensor2, trigger2);

//or even:

trigger.getSensorConfig.apply(trigger, sensor2, trigger2);

没事。您正在做的事情是 JavaScript 中的一种常见做法,并且一直在生产中使用。

于 2013-03-13T12:09:52.430 回答