我有一个模块,必须记录我想要添加的函数。我的问题是,因为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);
}
发布于 2014-05-30 19:30:53
更新:
抱歉,我一开始没听懂你在问什么。我看了一会儿,这是我能想到的最好的了。在构造函数中为每个实例创建记录方法并不理想,但同样,这也是我能想到的最好的方法。
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);
。
https://stackoverflow.com/questions/23961970
复制