删除超出作用域的函数中定义的监听器

remove listener defined in function thats out of scope

本文关键字:定义 监听器 函数 删除 作用域      更新时间:2023-09-26

我有一个模块,必须记录我想添加的功能。我的问题是,因为this.audio.stdout有另一个函数的侦听器设置,我只能删除启动函数调用时激活的侦听器,而不会搞乱其他进程。因为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);
}

UPDATE:

对不起,我一开始没明白你的意思。我看了一会儿,这是我能想到的最好的。像这样在构造函数中为每个实例创建record方法并不理想,但是,这是我能想到的最好的方法。
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);