[英]javascript remove event in handler,
请查看http://jsbin.com/nubeb/1/edit
(function(){
var func = function(e){
console.log("mouse move");
document.removeEventListener("mousemove",func);
};
document.addEventListener("mousemove",func);
console.log("working");
}());
我想知道,是否可以替换'func'
document.removeEventListener("mousemove",func);
对于其他一些关键字,我想写下面的代码
(function(){
document.addEventListener("mousemove",function(e){
document.removeEventListener("mousemove",***);
});
}());
我们有两个不同的选项,这里第一个是使用arguments.callee
,它将在不久的将来被弃用,使用arguments.callee
我们可以访问正在执行的当前函数,所以你可以这样做:
(function(){
document.addEventListener("mousemove",function mylistener(e){
document.removeEventListener("mousemove", arguments.callee);
});
}());
警告:第5版ECMAScript(ES5)禁止在严格模式下使用arguments.callee()。
阅读本文以获取更多信息: arguments.callee
如您所见,除了在不久的将来被弃用之外,您不能在strict mode
使用arguments.callee
,这会给我们带来一些麻烦。
我们有一个新的替代方案,它可以帮助我们不使用arguments.callee
。 好的,我们假设我们有这样的功能:
var myfunc = function yourfunc(){
//yourfunc is accessible
};
//but here yourfunc is not accessible
在这段代码中,我们只能在函数体中使用yourfunc
,但在那个上下文中我们只有myfunc
。 听起来我们在函数范围内有一个私有指针可以访问,可以用来代替arguments.callee
。
所以这是新的替代方案,也可以在strict mode
,因此在您的代码中,您可以这样做:
(function(){
document.addEventListener("mousemove",function mylistener(e){
document.removeEventListener("mousemove", mylistener);
});
}());
工作代码http://jsbin.com/wopitiba/1/edit?html,js,console,output
(function(){
document.addEventListener("mousemove",function(e){
console.log("mouse move");
document.removeEventListener("mousemove",arguments.callee);
});
console.log("working");
}());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.