0

I'm trying to bind a click event to a function; this happens into a REST get request :

$.get(Constants.webServices.rest.get.pointings(),params,function(data){
    var json = eval(data);
    for(var i=0; i<json.length;i++){
        [...]
        $('a').click(__applyPointing(json[i],originalParams))
        [...]
    }
}

But instead of simply binding, this code executes the function, which is for the moment:

__applyPointing: function(item,originalParams){
    console.log('applyPointing');
    console.log(item);
}

I also tried with bind('click') and on('click'), same result. My js debugger seems useless with an asynchronous request. Please advise.

1
  • You're calling the function, and passing its return value to bind against. You need to pass a reference to a function, meaning no () after you name it! F. Calderan's answer is good if you know what the parameters to your function are, as you do in this example. Commented Aug 8, 2012 at 15:57

1 Answer 1

4

try to change

$(a).click(__applyPointing(json[i],originalParams))

in

(function(i) {
    $(a).click(function() { __applyPointing(json[i],originalParams) })
}(i))

it's useful wrap the binding into a closure so json[i] is properly passed

Edit: please note that you wrote $(a) and maybe you may want to write $('a')

Sign up to request clarification or add additional context in comments.

3 Comments

Yes it could be, but it could also be a variable containing a DOM reference
Indeed, though I don't see any. I thought it might be worth mentioning.
Thanks a lot, it works. The $.get turns out to have nothing to do with my problem, I will edit my title. And indeed, my a is a variable containing a <a>. It's part of the [...], sorry about that, I will add it.

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.