Reputation: 44
I am trying to generalize a single function for handling different events in JavaScript. Meaning that depending on the event listener that was called my function needs to behave in a different way. However, I can only pass the reference to my function, which is where my problem arises.
In order for my function to behave properly I need to know which event handler called it. But if I can only pass by reference, I can't pass a parameter which tells me who the function caller was. So is there a way to pass a functions reference but also allow it to accept a parameter?
Here is some general code that hopefully illustrates my question.
btn1.AddEventListener("Click", myFunction);
btn2.AddEventListener("Click", myFunction);
function myFunction(caller){
if(caller == someObject)
{
//do something
}
else
{
//do something
}
}
Upvotes: 0
Views: 58
Reputation: 1049
Closure is useful for this kind of event handlers. To create a closure wrap the function call with another anonymous function like:
btn1.AddEventListener("Click", () => myFunction(btn1));
btn2.AddEventListener("Click", () => myFunction(btn2));
Also, you can pass additional arguments as much as you want like:
btn1.AddEventListener("Click", () => myFunction(btn1, another_param));
function myFunction(btn, param){
// ... do something with param.
}
With the traditional notation, this is equivalent to following:
btn1.AddEventListener("Click", function () {
return myFunction(btn1);
});
Upvotes: 1
Reputation: 370729
Inside the function, you can either examine the this
, which will refer to the element the listener was added to, or the first parameter (the event
)'s currentTarget
, which will refer to the same thing:
function myFunction(event) {
if (event.currentTarget === btn1) {
// btn1 was clicked
} else {
// btn2 was clicked
}
}
Upvotes: 2