Pass multiple arguments along with an event object to an event handler

好久不见. 提交于 2019-12-03 00:39:27

So if I understand correctly, you want to add an event listener to the element, and configure some additional data that exists at the time you're adding the listener to be passed to the listener when it's called. If that's what you want to do, you just need a proper closure. Something like this, assuming you want to store the additional data in an object:

var extra_data = {one: "One", two: "Two"};

var make_handler = function (extra_data) {
  return function (event) {
    // event and extra_data will be available here
  };
};

element.addEventListener("click", make_handler(extra_data));

I suspect you can't, but there is a trick:

element.clickArguments=new Object();
element.clickArguments.argument1=...;
element.clickArguments.argument2=...;

Now in your event handler reference the event emitting object.

helper function:

function curryRight( original ) {
    var args = [].slice.call( arguments, 1 );
    return function() {
        return original.apply( this, [].slice.call( arguments ).concat( args ) );
    };
}

Usage:

element.addEventListener("click", curryRight( eventHandler, 1, 2, 3 ), false );

Example:

function eventHandler( event, a, b, c ) {
    console.log( event, a, b, c );
    //Logs MouseEvent, 1, 2, 3
}

document.addEventListener("click", curryRight( eventHandler, 1, 2, 3 ), false );

I know this thread is old, but it's a common mistake I see here.

I have even tried using anonymous function inside addEventListener. Doing so, it seems that the control never reached to the closure inside the callback function.
--
@asur

You need to invoke the returned closure from eventHandler().

element.addEventListener("click", function(e){
    var data = {'event':e, 'args':arguments};
    eventHandler(data)();    // invoking the closure here
  }, false);

If you won't you just get a closure returned to the binary nirvana.

Besides that it's preferred to @jmm's solution while it's much more clean.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!