Keir Simmons
Keir Simmons

Reputation: 1684

Passing arguments to jQuery .click WHILST keeping event parameter

I need to use bind the click event to an element in the DOM whilst being able to pass arguments on the fly, including the event object. My current script uses the following:

var counter = 1;
$(".dynamo_user_info .dynamo_awards").each(function(){
    $(this).find("~ div a").each(function(){
        var id = $(this).attr("rel").split("aid-")[1];
        $(this).attr("id","dynamo_award-"+counter+"-"+id).bind('click',{c:counter,i:id},function(e){
            e.returnValue = e.preventDefault && e.preventDefault() ? false : false;
            dynamo.awards.tooltip.ini(c,i);
        });
    });
    counter++;
});

Now, as you can see, counter increases on each iteration and id does not hold a static value. After each iteration, the final values are: counter = 4, id = 2. Now whenever one of these elements is clicked, it preventDefaults as appropriate, then runs dynamo.awards.tooltip.ini(c,i);.

However, this does not work as intended. Instead of it running:

dynamo.awards.tooltip.ini(1,1); dynamo.awards.tooltip.ini(2,6);

etc (for example), it instead runs:

dynamo.awards.tooltip.ini(4,2); dynamo.awards.tooltip.ini(4,2);

i.e it uses the last stored values for counter and id. My guess is it does this due to how bind works, passing the parameters when the element is clicked, not before. I'm not sure how to fix this, unless I can trick the scope of the function in some way?

Upvotes: 1

Views: 153

Answers (1)

Musa
Musa

Reputation: 97672

The arguments are accessible through the event.data object , like

dynamo.awards.tooltip.ini(e.data.c, e.data.i);

http://api.jquery.com/bind/#passing-event-data

Upvotes: 2

Related Questions