Skip to content Skip to sidebar Skip to footer

Javascript Event, The Parameter "e" , "event" Or Other

My code: var transformString = Modernizr.prefixed('transform'); var inputDown, inputMove, inputUp; if (window.Touch) { inputDown = 'touchstart'; inputMove = 'touchmove'; in

Solution 1:

jQuery will call your event function and it will pass an event object into the argument. You don't need to worry about creating the variable, and you can give the argument any name you want (assuming it's a valid variable name).

The creation of the event object should be considered "black box", and you shouldn't worry about its exact structure or implementation. Just do what the docs and examples show you to do, and you'll be all right.

The key thing is to have a parameter in the function, though; otherwise, you won't have access to the event object jQuery passes.

As some other answers have stated, it's probably a good idea to avoid the name event, because if you're not careful you could conflict with a global variable of the same name on certain browsers. Instead, use e or similar and then you'll get a NameError if you forget to have a parameter in your function.

// Wrong way #1
$('.class').bind('click', function() {
    event.preventDefault();    // may attempt to call .preventDefault() on window.event if it exists
});

// Wrong way #2 (fails fast since e probably won't be on the global object)
$('.class').bind('click', function() {
    e.preventDefault();        // ReferenceError thrown here
});

// The correct way
$('.class').bind('click', function(e) {    // or (event) if you want, but the first example can bite you
    e.preventDefault();        // no problem
});

Solution 2:

jQuery passes a normalized, bug-fixed and featurized jQuery event object to your handler function as the first parameter. You should name this parameter e (or similar) so you never accidentally refer to the global window.event (Which is the native event object in chrome and IE) and get a quick error instead.


Solution 3:

The functions that reference e or event are callback functions. They are essentially called by jQuery itself and pass a variable as a result (you define the function there, but it calls it, assuming it's defined). That's why it can be either defined as e or event (it could be purple_elephant too).

Reference: http://en.wikipedia.org/wiki/Callback_(computer_programming)


Post a Comment for "Javascript Event, The Parameter "e" , "event" Or Other"