Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript event handler with parameters

I want to make an eventHandler that passes the event and some parameters. The problem is that the function doesn't get the element. Here is an example:

doClick = function(func){     var elem = .. // the element where it is all about     elem.onclick = function(e){         func(e, elem);     } } doClick(function(e, element){     // do stuff with element and the event }); 

The elem must be defined outside of anonymous function. How can i get the passed element to use within the anonymous function? Is there a way to do this?

And what about addEventListener? I don't seem to be able to pass the event through an addEventListener at all do I ?

Update

I seemed to fix the problem with 'this'

doClick = function(func){     var that = this;     this.element.onclick = function(e){         func(e, that);     } } 

Where this contains this.element that i can access in the function.

The addEventListener

But i'm wondering about the addEventListener:

function doClick(elem, func){     element.addEventListener('click', func(event, elem), false); } 
like image 901
sebas2day Avatar asked Apr 03 '12 19:04

sebas2day


People also ask

How do you pass parameters to an event handler?

If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.

How do you add an event listener to a variable?

To set up an event listener you just need to have a variable that references an element and then call the addEventListener function on that element. This function takes a minimum of two parameters. The first parameter is just a string which is the name of the event to listen to.

What is Eventlistener in JavaScript?

An event listener is a procedure in JavaScript that waits for an event to occur. The simple example of an event is a user clicking the mouse or pressing a key on the keyboard.

Can event handler return a value?

The standard signature of an event handler delegate defines a method that does not return a value. This method's first parameter is of type Object and refers to the instance that raises the event. Its second parameter is derived from type EventArgs and holds the event data.


2 Answers

I don't understand exactly what your code is trying to do, but you can make variables available in any event handler using the advantages of function closures:

function addClickHandler(elem, arg1, arg2) {     elem.addEventListener('click', function(e) {         // in the event handler function here, you can directly refer         // to arg1 and arg2 from the parent function arguments     }, false); } 

Depending upon your exact coding situation, you can pretty much always make some sort of closure preserve access to the variables for you.

From your comments, if what you're trying to accomplish is this:

element.addEventListener('click', func(event, this.elements[i])) 

Then, you could do this with a self executing function (IIFE) that captures the arguments you want in a closure as it executes and returns the actual event handler function:

element.addEventListener('click', (function(passedInElement) {     return function(e) {func(e, passedInElement); }; }) (this.elements[i]), false); 

For more info on how an IIFE works, see these other references:

Javascript wrapping code inside anonymous function

Immediately-Invoked Function Expression (IIFE) In JavaScript - Passing jQuery

What are good use cases for JavaScript self executing anonymous functions?

This last version is perhaps easier to see what it's doing like this:

// return our event handler while capturing an argument in the closure function handleEvent(passedInElement) {     return function(e) {         func(e, passedInElement);      }; }  element.addEventListener('click', handleEvent(this.elements[i])); 

It is also possible to use .bind() to add arguments to a callback. Any arguments you pass to .bind() will be prepended to the arguments that the callback itself will have. So, you could do this:

elem.addEventListener('click', function(a1, a2, e) {     // inside the event handler, you have access to both your arguments     // and the event object that the event handler passes }.bind(elem, arg1, arg2)); 
like image 72
jfriend00 Avatar answered Oct 10 '22 01:10

jfriend00


It is an old question but a common one. So let me add this one here.

With arrow function syntax you can achieve it more succinct way since it is lexically binded and can be chained.

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords.

const event_handler = (event, arg) => console.log(event, arg); el.addEventListener('click', (event) => event_handler(event, 'An argument')); 

If you need to clean up the event listener:

// Let's use use good old function sytax function event_handler(event, arg) {   console.log(event, arg); }  // Assign the listener callback to a variable var doClick = (event) => event_handler(event, 'An argument');   el.addEventListener('click', doClick);  // Do some work...  // Then later in the code, clean up el.removeEventListener('click', doClick); 

Here is crazy one-liner:

// You can replace console.log with some other callback function el.addEventListener('click', (event) => ((arg) => console.log(event, arg))('An argument')); 

More docile version: More appropriate for any sane work.

el.addEventListener('click', (event) => ((arg) => {   console.log(event, arg); })('An argument')); 
like image 32
snnsnn Avatar answered Oct 10 '22 02:10

snnsnn