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));
};
}
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With