为什么面向对象中addEventListener找不到属性或者无法移除事件?

以下两短代码都表示一个简单功能,描述为:我想要的效果是,鼠标按下后,在页面移动不断计数,鼠标抬起则移除事件。但是下面的代码都有问题。
第一段代码的问题,找不到removeEventListener属性:
functioncounter(obj){
this.obj=obj;
this.num=0;
}
counter.prototype.start=function(){
varself=this;
self.obj.addEventListener("mousemove",self.move,false);
self.obj.addEventListener("mouseup",self.end,false);
}
counter.prototype.move=function(){
varself=this;
document.title=self.num++;
}
counter.prototype.end=function(){
varself=this;
self.obj.removeEventListener("mousemove",self.move,false);
self.obj.removeEventListener("mouseup",self.end,false);
}
counter.prototype.init=function(){
varself=this;
self.obj.addEventListener("mousedown",self.start,false);
}
varcounterNew=newcounter(document);
counterNew.init();
以上代码在init中有修改,原来是self.end,搞错了,应该是self.start
第二段代码的问题,可能是因为绑定和删除都是匿名函数,所以无法移除事件:
functioncounter(obj){
this.obj=obj;
this.num=0;
}
counter.prototype.start=function(){
varself=this;
self.obj.addEventListener("mousemove",function(){
self.move();
},false);
self.obj.addEventListener("mouseup",function(){
self.end();
},false);
}
counter.prototype.move=function(){
varself=this;
document.title=self.num++;
}
counter.prototype.end=function(){
varself=this;
self.obj.removeEventListener("mousemove",function(){
self.move();
},false);
self.obj.removeEventListener("mouseup",function(){
self.end();
},false);
}
counter.prototype.init=function(){
varself=this;
self.obj.addEventListener("mousedown",function(){
self.start();
},false);
}
varcounterNew=newcounter(document);
counterNew.init();
请问大家,有解决方案吗?多谢了
九州编程
浏览 431回答 2
2回答

梦里花落0921

非面向对象实现//非面向对象实现varnum1=0;functionstart(){num1++;document.title=num1;}document.addEventListener("mousedown",function(){this.addEventListener("mousemove",start,false);},false);document.addEventListener("mouseup",function(){this.removeEventListener("mousemove",start,false);});面向对象实现functionCounter(obj){this.num=0;this.obj=obj;}Counter.prototype.countNum=function(){that.num++;this.title=that.num;}Counter.prototype.mdStart=function(){this.addEventListener("mousemove",that.countNum,false);}Counter.prototype.mdEnd=function(){this.removeEventListener("mousemove",that.countNum,false);}Counter.prototype.start=function(){that=this;this.obj.addEventListener("mousedown",that.mdStart,false);this.obj.addEventListener("mouseup",that.mdEnd,false);}Counter.prototype.end=function(){this.addEventListener("mouseup",this.mdEnd,false);}Counter.prototype.init=function(){this.start();}varcounterNew=newCounter(document);counterNew.init();第二种也可以通过call或者apply实现,TZ可以试试

陪伴而非守候

第一段代码解决方案:counter.prototype.init=function(){varself=this;self.obj.addEventListener("mousedown",function(){self.end();},false);}原因:self.obj.addEventListener("mousedown",self.end,false);,self.end函数中的this指向了document。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript