Question

What is the proper way to accomplish the following:

$("#btn").click(function1);

Calling the function:

function function1 (event) {
    event.preventDefault();
}

This seems to work, however I don't understand how function1 understands what the event argument is referring to without it being passed in. Wouldn't a listener set up like this make more sense:

$("#btn").click(function1(event));

Here is a fiddle.

Was it helpful?

Solution

The .click() function in jQuery except as first parameter a function. In Javascript function are value, as well as a primitive value or an object. Functions are first-class citizens.

If you use function1(event) as a parameter, the function will be executed, because this is the semantic of the brachet after the function name. So the .click() jQuery function will receive the output of the function, which is not the expected type.

Passing the function name as a parameter means that you are passing the function (actually, a reference to the function), not the result of the function invocation. And the function will be called when the click event will be triggered. The function in this case is called "callback".

Callbacks are very importants in Javascript, since the event-driven behaviour is the main reason for using a client-side scripting.

The concept behind the callback system is

//the click function
function doSomething(callback){
//in your case the event is the argument that jQuery will prepare for you
var argument = produceTheArgument();
//doSomething is in charge to invoke the function, passing the argument
callback(argument);
}

//your function
function myCallback(argument){
 //your function will consume the argument
}

//my callback is passed as a reference, not invoked
doSomething(myCallback);

OTHER TIPS

you are subscribing to event and passing a reference to the function inside click listener - the jQuery event processor will just call your function in jQuery's context and will pass all parameters to it.

In your first example function1 knows that the event variable is, because JavaScript (and subsequently jQuery) passes the event information as a parameter.

This is the nature of JavaScript, not just jQuery. Consider the following:

document.getElementById('btn').addEventListener('click', function1, false);

function function1(e)
{
    console.log(e);
}

JavaScript automatically calls function1 when #btn is clicked, and it automatically adds the event information as the first parameter. jQuery simply passes this information into its own methods as well, so that you have access to it.

According to jQuery's documentation:

The click event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed and released. Any HTML element can receive this event.

Reference: http://api.jquery.com/click/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top