Skip to content Skip to sidebar Skip to footer

How To Pass An Argument To The Listener Function Passed In Addeventlistener?

anItem.addEventListener('click', iRespond, false); problem is, I need to pass iRespond an argument because iRespond is supposed to handle clicks on many many items and I need a wa

Solution 1:

Simple closure:

var foo = "bar";
e.addEventListener('whee',function(evt){
  iRespond(evt,foo);
},false);

When a simple closure won't do (because you're latching onto a variable that's changing, such as in a loop) you need to create a new closure over that value:

foo.addEventListener('bar',(function(jim){
  returnfunction(evt){
    iRespond(evt,jim); // Surprise surprise, jim is available here!
  }
})(someValueToBeNamedJim), false);

For example:

var buttons = document.querySelectorAll('button');
for (var i=buttons.length;i--;)}
  buttons[i].addEventListener('click',(function(j){
    returnfunction(){ alert("You clicked on button #"+j); };
  })(i),false);
}

You can choose to name the variable the same both inside and outside the function without issue—e.g. using i instead of j above—but you may find yourself getting confused.

Solution 2:

Nobody seems to be offering the simplest solution. Put your other function call in an anonymous function like this:

anItem.addEventListener("click", function() {
    iRespond(your arg here);
}, false);

Or, in many cases, you can just reference the this pointer in the event listener to see what object you were called from:

anItem.addEventListener("click", iRespond, false);

Then, in iRespond:

function iRespond() {
    // this points to the item that caused the event so you can // determine which one you are processing and then act accordingly// For example, this.id is the id of the object
}

Solution 3:

There are many possibilities. No1 would be creating a closure for it. You also could use bind().

A better solution might be to distinguish the options (per item) by the target property of the event, which is also passed to the listener. This will become very elegant when you're using only one handler for many items, e.g. adding it to the <ul> instead of one for every <li> element. Then choose what to do e.g by id or data-attributes of the target element.

Post a Comment for "How To Pass An Argument To The Listener Function Passed In Addeventlistener?"