admin管理员组

文章数量:1426027

I'm relatively new to javascript and although I know what's causing the bug, I'm not sure how to refactor this to make it work.

for ( ... ) {
    var variableQueryValue = i

    addLink.bind('click', function() {
        $.ajax({
            type: 'POST',
            url: '/example',
            data: 'queryvalue=' + variableQueryValue,
            success: function(data) {
                console.log('Got into success method!');
            }
        });
    });
}

So basically we are binding a click event to some element whose data attribute is dependent on some variableQueryValue that changes every iteration. Because of the closure of the bind function handler, in the ajax request it will bind an event handler that uses the same value of variableQueryValue for each iteration.

How can I refactor this such that the updated variableQueryValue is taken into account?

Thanks for any help!

I'm relatively new to javascript and although I know what's causing the bug, I'm not sure how to refactor this to make it work.

for ( ... ) {
    var variableQueryValue = i

    addLink.bind('click', function() {
        $.ajax({
            type: 'POST',
            url: '/example',
            data: 'queryvalue=' + variableQueryValue,
            success: function(data) {
                console.log('Got into success method!');
            }
        });
    });
}

So basically we are binding a click event to some element whose data attribute is dependent on some variableQueryValue that changes every iteration. Because of the closure of the bind function handler, in the ajax request it will bind an event handler that uses the same value of variableQueryValue for each iteration.

How can I refactor this such that the updated variableQueryValue is taken into account?

Thanks for any help!

Share Improve this question asked Oct 3, 2011 at 19:07 PolandSpringPolandSpring 2,6747 gold badges26 silver badges35 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4
function create_handler( j ) {
    return function( e ) {
        $.ajax({
            type: 'POST',
            url: '/example',
            data: 'queryvalue=' + j,
            success: function(data) {
                console.log('Got into success method!');
            }
        });
    };
}

for ( ... ) {
    addLink.bind('click', create_handler( i ) );
}

Invoke a function that creates your handler, passing i into that function. Then have that function return the handler to be assigned to the .bind('click',....

This is because when you invoke a function, you create a new variable environment. So when you pass the value of i into the function, and create your handler inside that same function, your handler is now referencing the value that was passed into that specific variable environment.

The handler will retain the original variable environment in which it was created (even though you're returning the handler), so it will always reference the proper i value.


There are other solutions to the problem of retaining a persistent value used in a handler, but this resolves the specific closure issue. Depending on the actual situation, this may or may not be what you want to do.

Fundamentally, there is no reason to bind that to each link individually. Select the group and bind the event handler to the group.

Add whatever value you need to addLink via a call to .data() in the for loop. Then retrieve the value in the click event handler.

You need to close a variable with the value if i during each iteration of the for loop.

for ( ... ) {
    (function(variableQueryValue){
      addLink.bind('click', function() {
          $.ajax({
              type: 'POST',
              url: '/example',
              data: 'queryvalue=' + variableQueryValue,
              success: function(data) {
                  console.log('Got into success method!');
              }
          });
      });
    })(i);
}

Can you use .live() for this purpose?

The API says:

Description: Attach a handler to the event for all elements which match the current selector, now and in the future.

This I think would cater for the fact that your selector doesn't exists at the time you add the event...or have I misinterpreted?

You can wrap each callback to create closure:

addLink.bind((function(variableQueryValue) {
    return function() {

        // variableQueryValue can be used here
        $.ajax...
    };
}(variableQueryValue)));

This way, you will run the callback immediately that returns a new function wich has a local variable saved, so it can’t be changed from the outside.

本文标签: javascriptWorking Around Closure in JQuery quotajaxquot MethodStack Overflow