Skip to content Skip to sidebar Skip to footer

Jquery Closures, Loops And Events

I have a question similar to the one here: Event handlers inside a Javascript loop - need a closure? but I'm using jQuery and the solution given seems to fire the event when it's b

Solution 1:

You're missing a function. The .click function needs a function as a parameter so you need to do this:

.click(
    function(indGroup,indValue)
    {
        returnfunction()
        {
            jQuery(".IndicatorImage").removeClass("active");
            _this.Indicator.TrueImage = DisplayGlobals.Indicators[indGroup][indValue];
            _this.Indicator.FalseImage = DisplayGlobals.IndicatorsSpecial["BlankSmall"];
            jQuery(this).addClass("active"); 
        }
    }(i,j);
);

Solution 2:

Solution by Greg is still valid, but you can do it without creating additional closure now, by utilizing eventData parameter of jQuery click method (or bind or any other event-binding method, for that matter).

.click({indGroup: i, indValue : j}, function(event) {
    alert(event.data.indGroup);
    alert(event.data.indValue);
    ...
});

Looks much simpler and probably more efficient (one less closure per iteration).

Documentation for bind method has description and some examples on event data.

Solution 3:

Nikita's answer works fine as long as you are using jQuery 1.4.3 and later. For versions previous to this (back to 1.0) you will have to use bind as follows:

.bind('click', {indGroup: i, indValue : j}, function(event) {
    alert(event.data.indGroup);
    alert(event.data.indValue);
    ...
});

Hope this helps anyone else still using 1.4.2 (like me)

Post a Comment for "Jquery Closures, Loops And Events"