Moojjoo
Moojjoo

Reputation: 753

jQuery - Function Parameters

I read the following, but still want to discuss.... Meaning of evt = (evt) ? evt : window.event

//Would evt need to be passed because it is not used in the function??? --- Trying to get my mind wrapped around this jQuery stuff.

A)

$('#' + _ids.btnPrintServiceCode).on('click', function (evt) {
        alert('Hello World')
    });

OR

B)

$('#' + _ids.btnPrintServiceCode).on('click', function () {
        alert('Hello World')
    });

Upvotes: 0

Views: 933

Answers (2)

bipen
bipen

Reputation: 36531

You don't need to pass the evt if it is not used, it is optional. However having it won't create an issue.

You basically pass evt if you need to listen to the event. Say you want to prevent the default behaviour of some elements, so you need evt here.

HTML

<a href="#"></a>

jQuery

$('a').on('click', function (evt) {
    evt.preventDefault(); // this will prevent the default behaviour of that element
    alert('Hello World');
});

$('input').keyup(function(e){ //here we need to pass e as we are using e to get the keyCode that was pressed
   if(e.keyCode == 8 )
   {
        alert('test');
    }
});

Upvotes: 3

Kevin B
Kevin B

Reputation: 95022

Think of it this way. Lets say i have this function:

function foo (bar) {
    alert("worky");
}
foo("foobar"); // worky

Since inside the function i'm never actually using bar, i can simplify the function by removing bar from the parameter list.

function foo () {
    alert("worky");
}
foo("foobar"); // worky

both will have the same result. The same is true with your event binding. Since you are never using evt, there is no reason for you to pass it to the function, however it won't hurt anything if you do anyway.

If the previous developer always passed evt to event handler callbacks, you should continue to do so to keep the code consistent, but that's entirely up to you.

Upvotes: 1

Related Questions