pHneutre
pHneutre

Reputation: 1171

jQuery: click() executes instead of binding

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.

Upvotes: 0

Views: 103

Answers (1)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123367

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')

Upvotes: 4

Related Questions