Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How can one pass multiple arguments along with an event object to an event handler without using Function.prototype.bind?

The event handler has a closure in it.

The below basic code won't work,

element.addEventListener("click", eventHandler(eventObj + arguments), false);

function eventHandler(eventObj + arguments) {
  return function(){}; //a closure
}

I don't know how to pass event object and other arguments at the same time to an event handler.

Updated:

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.

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

function eventHandler(data) {
  return function(){  //this function is never executed
    console.log(JSON.stringify(data));
  };
}
like image 914
Asur Avatar asked Jan 20 '12 12:01

Asur


3 Answers

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));
like image 107
JMM Avatar answered Nov 17 '22 17:11

JMM


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.

like image 32
Eugen Rieck Avatar answered Nov 17 '22 17:11

Eugen Rieck


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 );
like image 1
Esailija Avatar answered Nov 17 '22 17:11

Esailija