2

I have a situation where I'm using a package/plugin that has a bind function.

I call the bind with a code which is the filter for when myevents fires callbacks. In this senario, three calls will be made to bind, one with parameter 't1', the second for 't2' and the third for 't3'.

When an event is fired from the myevents object, the callback is called (depending on the code) with the data parameter.

My issue is when the callback function is called, I need to know the index number of the loop when it was originally bound. For example, I have the i variable in the alert statement but I dont' know how to get the value there to save for when the callback is eventually fired.

Seems like there would be some combination of "function(data,i)" to accomplish this.

bindList = array('t1','t2','t3');

for (var i = 0; i < bindList.length; i++) {
        myevents.bind(bindList[i], function(data) {
            alert('data arrive on item ' + i + ': ' + data);
        });
    }

I would appreciate any help. Thanks.

1 Answer 1

5

Use a closure. Since JS variables are "function scoped", the i at 0 refers to the same i at any point in the iteration. We need to create a scope for each iteration so that the binding code refers to the closure's i rather than the loop's i.

for (var i = 0; i < bindList.length; i++) {
  (function(i){
    myevents.bind(bindList[i], function(data) {
      alert('data arrive on item ' + i + ': ' + data);
    });
  }(i));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Just a small explanation: in the original code i refers to the outside variable, so by the time the callback gets executed the loop finished and all callbacks will use the same value bindList.length.
Thank you! Joseph's and Wahl's were great answers. Tried this one and it works. So easy... so slick! THanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.