Javascript 将原型函数注册为回调函数
我已经添加了一个带有Javascript 将原型函数注册为回调函数,javascript,frontend,Javascript,Frontend,我已经添加了一个带有document.addEventListener的keydown事件侦听器,我想稍后通过调用document.removeEventListener将其删除到其他地方 我知道这听起来很简单,但因为我正在编辑一些生成的代码,而且生成器似乎喜欢prototype,所以所有代码都是基于prototype的。以下是简化版: 首先,我让这个对象说函数A(){XXX},我在原型中添加了一个侦听器函数: A.prototype.listener = function () {consol
document.addEventListener
的keydown事件侦听器,我想稍后通过调用document.removeEventListener
将其删除到其他地方
我知道这听起来很简单,但因为我正在编辑一些生成的代码,而且生成器似乎喜欢prototype,所以所有代码都是基于prototype的。以下是简化版:
首先,我让这个对象说函数A(){XXX}
,我在原型中添加了一个侦听器函数:
A.prototype.listener = function () {console.log(this);}
原型中有一个listen
方法
A.prototype.listen = function() {
document.addEventListener "keydown", KeyboardInputManager.prototype.listener
}
最后,还有一个stopListen
方法:
A.prototype.stopListen = function() {
document.removeEventListener "keydown", KeyboardInputManager.prototype.listener
}
这里有两个问题,第一,即使调用了stopListen
方法,事件仍然被发布,第二,在我的listener
方法中,我想调用A
的一些其他原型方法,但其中的this
变量是传递给侦听器的文档(这是我的猜测,如果我错了,请纠正我)
因此,我不知道如何解决这个问题,请帮我离开这里!当您在特定事件上使用addEventListener()
附加方法(object.methodName
)时,该对象将在该事件发生时丢失,并且此
引用将是全局对象document
function A() {
console.log("someProperty");
}
A.prototype.newMethod = function () {
console.log('new method');
}
A.prototype.listener = function () {
this.newMethod();
}
A.prototype.listen = function() {
document.addEventListener( "keydown", callFunc);
}
function callFunc(){
myObj.listener(); //now inside listener() this refers actual object
}
A.prototype.stopListen = function() {
document.removeEventListener("keydown", callFunc);
}
var myObj = new A();
myObj.listen();
myObj.stopListen();
这里有两个问题,第一,即使调用了stopListen方法,事件仍然被发布
发布的代码有语法错误:
> document.removeEventListener "keydown", KeyboardInputManager.prototype.listener
应该是:
document.removeEventListener("keydown", KeyboardInputManager.prototype.listener);
如果看不到更多的代码,就无法确定这为什么不起作用
我想调用A的其他一些原型方法,但其中的this var是传递给侦听器的文档
因为当使用addEventListener将函数附加为侦听器时,函数中的这个对象就是侦听器附加到的DOM对象
A.prototype.listen = function() {
document.addEventListener("keydown", function() {
KeyboardInputManager.prototype.listener.call(A);
});
}
但是,您如何不引用函数来删除侦听器。有关如何修复此问题的想法,请参阅Suman的答案(即附加一个命名函数,用于调用侦听器并将其设置为所需的值)。您能否在jsfiddle上提供完整的代码?