Javascript 如何正确删除类中的事件侦听器?
我在Windows7中使用node.js 8.9.3。我正在编写一个类,它使用流和Javascript 如何正确删除类中的事件侦听器?,javascript,node.js,dom-events,Javascript,Node.js,Dom Events,我在Windows7中使用node.js 8.9.3。我正在编写一个类,它使用流和bylinenpm包在构造函数中自动读取文件的第一部分(“头”)。标题中的数据通过事件处理和署名中的本机数据事件传递给处理函数。读取文件头中的最后一行后,应暂停流,删除数据事件的现有侦听器,并添加另一个使用不同处理功能的侦听器。所以本质上我是在用另一个函数替换一个处理函数 我遇到的问题是,即使我试图专门删除标题处理函数,并且成功地附加了后续处理函数,标题函数在删除后仍会继续处理数据事件中的行。换句话说,即使在使用r
byline
npm包在构造函数中自动读取文件的第一部分(“头”)。标题中的数据通过事件处理和署名
中的本机数据
事件传递给处理函数。读取文件头中的最后一行后,应暂停流,删除数据
事件的现有侦听器,并添加另一个使用不同处理功能的侦听器。所以本质上我是在用另一个函数替换一个处理函数
我遇到的问题是,即使我试图专门删除标题处理函数,并且成功地附加了后续处理函数,标题函数在删除后仍会继续处理数据事件中的行。换句话说,即使在使用removeListener
这是我的代码,删除了不相关的部分:
const fs = require('fs'),
path = require('path'),
byline = require('byline'),
EventEmitter = require('events');
class VCFStream extends EventEmitter{
constructor(vcfPath){
super();
this.header = [];
this.variants = {};
this.stream = byline.createStream(fs.createReadStream(
vcfPath, { encoding: 'utf8' }));
this.stream.on('data', this.headerParse.bind(this));
this.stream.on('end', function(){
console.log('Stream is done');
self.emit('end');
});
}
headerParse(line){
var self = this;
if(line.startsWith('#CHROM')){
//This is the last line of the header.
line.split('\t').splice(9).forEach(function(samp){
self.samples.push(samp);
});
this.stream.pause();
// I've also tried using this.headerParse
// and this.headerParse.bind(this)
// and this.headerParse()
this.stream.removeListener('data', self.headerParse);
//Attaching the event listener to process new data after the header
this.stream.on('data', self.variantParse.bind(self));
this.header.push(line);
this.emit('header');
console.log('header');
return;
}
this.header.push(line);
}
variantParse(line){
let contig = line.split('\t')[0];
if(!this.variants.hasOwnProperty(contig)){
this.variants[contig] = [];
}
this.variants[contig].push(line);
}
/*
I've also tried using the below class method,
calling this.removeHeaderListener() instead of
this.stream.removeListener('data', self.headerParse);
*/
removeHeaderListener(){
this.stream.removeListener('data', this.headerParse);
}
}
module.exports = VCFStream;
如果我在headerParse()
方法中粘贴console.log(line)
,则在删除侦听器后,它将继续记录每一行事件。您需要存储绑定的函数以准确删除该对象。调用bind()
可能是正确的想法,但再次调用它确实会产生一个新函数。@Bergi您是对的,这确实使这成为一个重复的问题。非常感谢。