g-pdx
g-pdx

Reputation: 37

jQuery bind inside a for loop variable scope

I know this question has been asked many times but I haven't been able to resolve from what I found on Stack O. Here is my code

for(var i=0; i<retrievedSearchesListLength; i++){
retrievedSearchesListProv = retrievedSearchesList[i].searchId;
retrievedSearchesListType = retrievedSearchesList[i].searchParameters;

    function getEventHandlerFunction(a){
    $J.cookies.set('ps_clickedsearch',a);
}

 $J('#submitSearch'+i).bind('click',getEventHandlerFunction(retrievedSearchesListType));
}

Everytime the resulting value is the last for loop value. How do I keep scope so that the link clicked results in the correct value?

I need the correct retrievedSearchesListType to reflect when the link is clicked.

Thanks in advance

Upvotes: 0

Views: 137

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You need to return the callback method from getEventHandlerFunction

for(var i=0; i<retrievedSearchesListLength; i++){
    retrievedSearchesListProv = retrievedSearchesList[i].searchId;
    retrievedSearchesListType = retrievedSearchesList[i].searchParameters;

    function getEventHandlerFunction(a){
        return function(){
            $J.cookies.set('ps_clickedsearch',a);
        }
    }

    $J('#submitSearch'+i).bind('click',getEventHandlerFunction(retrievedSearchesListType));
}

Upvotes: 1

Related Questions