是否有一个工作周围的addEventListener回调与返回值? [英] Is there a work around for addEventListener callbacks with return value?
问题描述
我目前正在尝试自定义(2级DOM)事件,我现在已经得到的问题, addEventListener()
不会接受返回值的回调 - 或者至少我不熟悉这个正确的方法。
I'm currently experimenting with custom (level 2 DOM) events and I've now arrived at the problem that addEventListener()
will not accept callbacks that return a value -- or at least I'm unfamiliar with the proper approach to this.
基本上我想要的是:
addEventListener("customEvent",
function() {
return true ;
},
false) ;
,因此如果我创建一个包装函数的实例 new wrapper
,
so that if I create an instance of a wrapper function new wrapper()
,
function wrapper() {
addEventListener(...) ;
}
这将正确返回, true
每当事件被触发和捕获。
this will properly return, true
whenever the event is triggered and caught.
请记住,这是实验性的:我知道有很多解决方案,不需要从 addEventListener
方法返回。
Please keep in mind that this is experimental: I am aware that there are a plethora of solutions that do not require a return from an addEventListener
method. I'm just curious whether there is a work-around or if this is in fact a dead-end and I should not bother.
感谢您的帮助!
推荐答案
AddEventListener按规范不会也不会返回值。如果addEventListener返回一个值,那么它将是无用的,因为触发callbackFunction的事件将获得返回值,而不是仅仅注册它的addEventListener。
AddEventListener by specification does not and will not return a value. If addEventListener were to return a value, it would be useless as the event that triggers the callbackFunction would get the return value and not to addEventListener which merely registered it.
addEventListener( 'onload', function() {
// do something
return true;
// bool(true) would be returned to window.event[onload] and not to addEventListener if that were the case which would still make it useless to you.
}, false );
有了这个说法,有一个脏的方法,但它应该得到你想要的。 p>
With that being said, there is a dirty method but it should get you what you want.
var eventTracker = {
retVal: false,
retEvt: false,
trigger: function( e ) {
e = e || window.event;
// some code here
}
};
function someFn(e) {
e = e || window.event;
// Some code here
eventTracker.retVal = true;
eventTracker.retEvt = e.type;
eventTracker.trigger.call( e );
}
// Bind the event in all browsers
if ( window.addEventListener ) {
window.addEventListener( 'load', someFn, false );
} else if ( window.attachEvent ) {
window.attachEvent( 'onload', someFn );
} else {
window.onload = someFn;
}
这篇关于是否有一个工作周围的addEventListener回调与返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!