[英]How to handle single JavaScript events intuitively?
I often need to create single events that are not needed after they have run once.我经常需要创建运行一次后不需要的单个事件。 The way I do is something like:
我的做法是这样的:
A.prototype.someMethod = function () {
var me = this;
this.onWindowMouseUpFunction = function () {
me.onWindowMouseUp.apply(me, arguments);
};
window.addEventListener('mouseup', this.onWindowMouseUpFunction, false);
}
A.prototype.onWindowMouseUp = function () {
window.removeEventListener('mouseup', this.onWindowMouseUpFunction, false);
}
However, since the event logic is split into two methods and I cannot use anonymous functions and instead have to assign the function to a variable, I have begun to think that there must be a better way of doing this, right?但是,由于事件逻辑分为两种方法,我不能使用匿名函数,而是必须将函数分配给一个变量,我开始认为必须有更好的方法来做到这一点,对吧?
I think your best shot is to create a wrapper function that does all this automatically.我认为你最好的办法是创建一个自动完成所有这些的包装函数。
Something like就像是
function addOneTimeEventListener(objToListenOn, eventtype, callbackfunction){
var callThenRemove = function() {
callbackfunction();
objToListenOn.removeEventListener(eventtype, callThenRemove, false);
};
objToListenOn.addEventListener(eventtype, callThenRemove, false);
};
Usage用法
addOneTimeEventListener(window, "mouseup", function(){/*tada, anonymus function*/});
Simply do this:只需这样做:
A.prototype.someMethod = function () {
function onMouseUp() {
// do stuff ...
// then remove event listener
window.removeEventListener('mouseup', onMouseUp, false);
}
window.addEventListener('mouseup', onMouseUp, false);
}
There's less typing involved and your event listener becomes private.涉及的输入更少,您的事件侦听器变得私密。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.