views:

64

answers:

3

The following code renders 3 buttons with label "1", "2" and "3". Clicking on each button will alert the label.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&gt;&lt;/script&gt;
        <script type="text/javascript">
            $(function() {
                var a = [1, 2, 3];
                $.each(a, function(i, ai) {
                    $('<button />').text(i).appendTo('body')
                        .click(function() {alert(i);});
                });
            });
        </script>
    </head>
    <body>
    </body>
</html>

However, if I replace function() {alert(i);} with foo and define function foo() { alert(i); }, I will get an error of variable i is not defined.

So how to pass parameters (other than event) to event handlers? I think defining the event handler (foo() in this case) as a named function will make the code cleaner if the event handler is long and complicated.

+2  A: 
$(function() {
                var a = [1, 2, 3];
                $.each(a, function(i, ai) {
                    $('<button />').text(i).appendTo('body')
                        .click(function() { foo.apply(this,[i]);});
                });
            });


function foo( i )
{
   alert( i + " : " + $(this).text() );
}
Ghommey
Shouldn't it be `foo.call`? `apply` takes an array.
Matthew Flaschen
@Matthew Flaschen: thx - I fixed that.
Ghommey
@Ghommey, why create an array? `foo.call(this, i);` would be a bit simpler.
Matthew Flaschen
I like this answer. The most succinct one IMO. I guess Ghommey use `apply()` instead of `call()` because `apply()` can be used for passing multiple parameters which is a more general case.
powerboy
@powerboy - Both can be used to pass multiple arguments. `apply()` requires the data to be packed in an array, while `call()` can take any number of arguments after the scope parameter. So these two statements are equivalent: `myfunction.apply(this,[1,2,3,'four'])` and `myfunction.call(this,1,2,3,'four')`. In practice, I've found it easier and more natural to use `call()`.
Andrew
+2  A: 

A third method, and the way I usually do it is to invoke a function that returns your handler. Like this:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&gt;&lt;/script&gt;
        <script type="text/javascript">
            var bindFoo = function(x) {
                return function() {alert(x);};
            };
            $(function() {
                var a = [1, 2, 3];
                $.each(a, function(i, ai) {
                    $('<button />').text(i).appendTo('body')
                        .click(bindFoo(i));
                });
            });
        </script>
    </head>
    <body>
    </body>
</html>

I'm using x in the binding function only to distinguish it from i in the main code block.

Andrew
+3  A: 

If you look at the documentation for bind, you'll see it has an optional eventData parameter. So for example this would work:

function foo(e)
{
    alert(e.data.theI);
}

$(function ()
{
    var a = [1, 2, 3];
    $.each(a, function (i, ai)
    {
        $('<button/>').text(i).appendTo('body').bind("click", {theI: i}, foo);
    });
});
Domenic