BviLLe_Kid BviLLe_Kid - 5 months ago 14
Javascript Question

Understanding handler in jQuery

In my code I have this:

<script type="text/javascript">
$(document).ready(function (e) {
$('#EventCreate').click(function (e) {
location.href = '@Url.Action("Create", "AEvents")';
});
});
</script>

<button id="EventCreate" type="button" class="btn btn-info" style="float:right;">Create New Event</button>


Now this works perfectly, but my mission is to understand all aspects of why it works.

I have done some reading here but it is not yet settling in my head. Also, in the reference, all of the examples that are provided don't have a handler.

I have also tried debugging to see what the
e
has/is but have had 0 luck.

My question is why have the
e
? I know that the
e
is an event handler but would this work:

<script type="text/javascript">
$(document).ready(function (/* no event handler */) {
$('#EventCreate').click(function (/* no event handler */) {
location.href = '@Url.Action("Create", "AEvents")';
});
});
</script>


Any help/explanation would be greatly appreciated.

Answer

e / event / evt in that context is actually an Event Object, NOT an event handler. It's the argument that's passed into an event handler/listeners callback function.

This represents the state of that event when it occurred and provides valuable context to the actual event. It is only necessary to inlcude when you require the context data of the event itself. Otherwise it can be omitted, as you can do with most unneeded arguments in JavaScript.

For example, take a simple input handler:

document
  .getElementById('example')
  .addEventListener('change', onChange, false);

function onChange(e) {
  console.log(e.target.value); // value of input
}
<label>Example input</label>
<input type="text" id="example" placeholder="Example."/>

When you bind a listener to the change event, you can access the e argument which is an Event Object. With that object, you have the ability to read the current value of the input after was changed.