开发者

Is there a work around for addEventListener callbacks with return value?

开发者 https://www.devze.com 2022-12-25 18:12 出处:网络
I\'m currently experimenting with custom (level 2 DOM) events a开发者_JS百科nd I\'ve now arrived at the problem that addEventListener() will not accept callbacks that return a value -- or at least I\'

I'm currently experimenting with custom (level 2 DOM) events a开发者_JS百科nd 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.

Basically what I want is this:

    addEventListener("customEvent",
        function() {
            return true ;
         },
    false) ;

so that if I create an instance of a wrapper function new wrapper(),

     function wrapper() {
         addEventListener(...) ;
     }

this will properly return, true whenever the event is triggered and caught.

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 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 );

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消