ariel
ariel

Reputation: 16150

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

Upvotes: 2

Views: 7767

Answers (2)

Beetroot-Beetroot
Beetroot-Beetroot

Reputation: 18078

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.

Upvotes: 1

devang
devang

Reputation: 5516

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.

Upvotes: 8

Related Questions