nodejs事件原型及其范围使用that = this

时间:2013-03-13 11:43:52

标签: node.js scope prototypal-inheritance eventemitter

我正在尝试使用其统一系统在Nodejs中进行开发。我已经实现了以下代码,它通过了我的测试(使用mocha)。但是,由于that变量的范围,我不相信它会在生产环境中起作用。

在我的代码中,我指定that=this。然后,我将config对象分配给that.config,并且回调会发出事件而不会将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"
}

1 个答案:

答案 0 :(得分:0)

仅当下次运行时,“that”才会更改为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中的常见做法,并且一直用于生产。

相关问题