Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a parameter to a event handler in jQuery

How I send to the handler a variable that's on the outer scope?

i = 1;
$(id).change(function() {myHandler(i)});
i = 2;

When called, the parameter is 2.

Also tried as string, that work in DOM but dont work in jQuery:

$(id).change('myHandler(' + i + ')');
like image 681
ariel Avatar asked Feb 27 '26 12:02

ariel


2 Answers

Say you want to pass data object,

var data = {i: 2};
$(id).change(data, myHandler);

In the myHandler function:

function myHandler(event) {
    var i = event.data.i; // <= your data
}

The value passes as parameter if modified later wont get reflected.

like image 133
devang Avatar answered Mar 01 '26 02:03

devang


By calling a function that accepts i as an argument and returns a function, you can make a closure that traps the current value of i.

function changeHandlerClosure(i) {
    return function() {
        //do stuff here with i
    };
}

i = 1;
$(id).change(changeHandlerClosure(i));
i = 2;

This avoids interacting with the DOM, which is sometimes more convenient but slower.

like image 29
Beetroot-Beetroot Avatar answered Mar 01 '26 01:03

Beetroot-Beetroot