Dyin
Dyin

Reputation: 5376

Creating callback functions dynamically for a set of elements

The variable myCollection holds jQuery DOM elements, and I want to set a callback function for each of their onclick event as shows below. Actually what I want is, to incrementally set or could say "burn" the number for each element, so when they are getting clicked, its own number would get alerted. This code alerts the last value of number when it was incremented in the loop the last time.

var number = 1;

myCollection.each(function(){
    this.onclick = function() { someFunction(number) };
    number++;
});

//This function is somewhere else, but accessible.
function someFunction(number) {
    alert(number);
}

How can I copy or instantiate callback functions for each elements, so they would have the same process but with different arguments bind to them?

Upvotes: 1

Views: 1975

Answers (1)

David Hellsing
David Hellsing

Reputation: 108530

A classic scoping problem, it can be solved like this:

myCollection.each(function(){
  this.onclick=(function(number) {
      // in this scope, number has been "burned"
      return function() {
          someFunction(number)
      };
  }(number));
  number++;
});

Note that jQuery already includes a correctly scoped index inside the each callback, so all you need to do is:

myCollection.each(function(i){
    $(this).click(function(){
        someFunction(i+1);
    });
});

Upvotes: 3

Related Questions