删除函数中定义的侦听器超出范围

时间:2014-05-30 19:19:44

标签: javascript node.js

我有一个模块,必须记录我想要添加的功能。我的问题是因为this.audio.stdout为另一个函数设置了一个监听器,我只能删除在调用start函数时激活的监听器,而不会搞砸其他进程。因为filename的值根据调用函数的时间而改变,所以我必须在设置该值时的范围内定义回调。这适用于使用start()开始录制,但是当我调用stop()(删除侦听器)时,程序不知道该怎么做,因为回调超出了范围。这样做的正确方法是什么?

function Record(rx) {
    this.rx = rx;
    this.audio = spawn('audio_client');
}

Record.prototype.start = function () {
    var self = this;
    self.filename= new Date().getTime()+'_'+this.rx

    function record(data) {
        console.log(self.filename);
    }
    this.audio.stdout.on('data', record);
}

Record.prototype.stop = function () {
    this.audio.stdout.removeListener('data',record);
}

1 个答案:

答案 0 :(得分:0)

<强>更新

抱歉,我一开始并不明白你的要求。我看了一下这个,这是我能想到的最好的。在这样的构造函数中为每个实例创建记录方法并不理想,但同样,这是我能想到的最好的。

function Record(rx) {
    this.rx = rx;
    this.audio = spawn('audio_client');

    var self = this;
    this.record = function (data) {
        console.log(self.filename);
    };
}

Record.prototype.start = function () {
    this.filename= new Date().getTime()+'_'+this.rx
    this.audio.stdout.on('data', this.record);
};

Record.prototype.stop = function () {
    this.audio.stdout.removeListener('data', this.record);
};

更新#2:

更好的是因为您特定于节点,因此this.record = this.record.bind(this);