JavaScript Event Handler with Parameters

What exactly is the parameter e (event) and why pass it to JavaScript functions?

The e is short for event

The simplest way to create an event is to click somewhere on the page.

When you click, a click event is triggered. This event is actually an object containing information about the action that just happened. In this example's case, the event would have info such as the coordinates of the click (event.screenX for example), the element on which you clicked (event.target), and much more.

Now, events happen all the time, however you are not interested in all the events that happen. When you are interested in some event however, it's when you add an event listener to the element you know will create events[1]. For example you are interested in knowing when the user clicks on a 'Subscribe' button and you want to do something when this event happens.

In order to do something about this event you bind an event handler to the button you are interested in. The way to bind the handler to the element is by doing element.addEventListener(eventName, handler).

eventName is a string and it's the name of the event you are interested in, in this case that would be 'click' (for the "click" event).

The handler is simply a function which does something (it's executed) when the event happens. The handler function, by default, when executed is passed the event object (that was created when the event/action you are interested in happened) as an argument.

Defining the event as a parameter of your handler function is optional but, sometimes (most times), it is useful for the handler function to know about the event that happened. When you do define it this is the e you see in the functions like the ones you mentioned. Remember, the event is just a regular javascript object, with lots of properties on it.

Hope that helped.

For more info read Creating and Triggering Events

As for your 3rd question, now you should know you cannot do that, because e only exists when an event happens. You could have the handler function, which has access to the e object when it gets executed, to store it in some global variable and work on that.

[1] That is not exactly correct, but it's simpler to understand. The more correct thing to say there is "add an event listener to the element you know will have events flow through it". See this for more information

Passing a parameter into an event handler

You must pass a function or a function reference to an event binding expression so if you need to pass arguments, you can wrap the actual function call (with parameters) in an anonymous function and pass that to the event binding expression.

let bank = {  deposit:50};
$('#checkingDeposit').on('click', function(event) { deposit(event, {amount:100, account:'savings'}, bank.deposit)}); function deposit(event, obj, account){ console.log('deposit running'); console.log(obj.account); //output 'savings' console.log(obj.amount); //output 100}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><button type="button" id="checkingDeposit">Deposit</button>

Pass additional arguments to event handler?

You can use bind for that. Here is an example:

element.on('click', this._clickHandler.bind(this));

//later in the code...

_clickHandler: function(event) {

}

Since you're using jQuery though, you can also use jQuery.proxy() too. More here: http://api.jquery.com/jQuery.proxy

Update:

To get access to the element inside the callback you would have to use event.target or event.currentTarget or do the following (depends on what you're doing):

element.on('click', this._clickHandler.bind(this, element));

//later in the code...

_clickHandler: function(element, event) {

}

Another way is to set the element as a property of the object like: this.element = $('#el') and then use that in your callback(s).

Live example: http://jsbin.com/mezuberucu/1/edit?html,js,output

How to pass arguments to addEventListener listener function?

There is absolutely nothing wrong with the code you've written. Both some_function and someVar should be accessible, in case they were available in the context where anonymous

function() { some_function(someVar); } 

was created.

Check if the alert gives you the value you've been looking for, be sure it will be accessible in the scope of anonymous function (unless you have more code that operates on the same someVar variable next to the call to addEventListener)

var someVar; 
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);

Event parameter with another parameter in JS

Just accept it in the event listener, and pass it to your function:

input.addEventListener('click', function(e) {
a(e, 4);
});

With this code, the return in a is useless, though, since the value isn’t captured anywhere. You’d need to use that return value somehow, e.g. by logging it with console.log(a(e, 4));.

How to decide when to pass parameter & when not

Events like onClick, onChange and others will pass an "event" parameter (could be event, e, or whatever name you give to it) by default to your event handler.

The thing is, if you want to pass custom parameters too, the handler will receive them but this default event won't be accesible, unless you pass it too.

You can see an example with 3 different scenarios here

  • Receive only the event. No need to pass it:
onClick={() => this.nameChangedHandler()} />
  • Receive both the event, plus custom parameters (id is state in this example)
onClick={(event) => this.nameChangedHandler(event, id)} />
  • Pass only a custom parameter, but don't receive event
onClick={() => this.nameChangedHandler(id)} />

Pass parameters to event listener that can be removed javascript

You need to have a standalone reference to the function you pass into addEventListener. For example:

var parameter = "";
const callback = function(e){
function_To_Call(e,parameter);
}
myVar.addEventListener('event', callback);
// ...
myVar.removeEventListener('event', callback);

Whether parameter changes in the meantime is of no consequence, because the callback function is still static.

Note that to reduce unnecessary code, feel free to omit the third parameter to addEventListener, useCapture, which defaults to false already.

Add an event listener with parameters and then remove it

You should store the currently anonymous function into a variable, so that you can call removeEventListener with it later:

const launchKittyTrue = () => { this.launchKitty(true) };
fancyButton.addEventListener('click', launchKittyTrue, true);
// later:
fancyButton.removeEventListener('click', launchKittyTrue, true);

To be more flexible, you might consider a Map indexed by arguments, whose values are the bound functions:

const boundFns = new Map();
function makeListener(arg) {
if (!boundFns.has(arg)) {
boundFns.set(arg, launchKitty.bind(undefined, arg));
}
return boundFns.get(arg);
}
function getListener(arg) {
return boundFns.get(arg);
}
fancyButton.addEventListener('click', makeListener(true), true);
// later:
fancyButton.removeEventListener('click', getListener(true), true);


Related Topics



Leave a reply



Submit