Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript parameter passing in dynamic action handler

Tags:

javascript

I need to create several Divs dynamically, and I need to add "onmouseover" event to them. However, the JAVASCRIPT "div.onmouseover = handler" can't pass in parameters. how can I pass parameters in those dynamic event handlers?

like image 238
Sefler Avatar asked Feb 19 '26 05:02

Sefler


2 Answers

You can take advantage of closures to do this:

function createHandlerFor(a, b, c) {
    return function(event) {
        // This function will be called later, and it has access
        // to 'a', 'b', and 'c'
    };
}

Or using a named function (my preference, so call stacks and such are clearer);

function createHandlerFor(a, b, c) {
    function myNiftyHandler(event) {
        // This function will be called later, and it has access
        // to 'a', 'b', and 'c'
    };
    return myNiftyHandler;
}

Use:

div.onmouseover = createHandler(1, 2, "three");

...or hook it up via addEventListener (standards) or attachEvent (IE < 8).

Although you could define the handler inline, doing so "closes over" everything that's in scope where you define it. Using a separate function and passing it parameters keeps the closure as small as possible, which is useful for memory management.

Closures are not complicated, but they have some interesting properties. More here.

like image 95
T.J. Crowder Avatar answered Feb 21 '26 19:02

T.J. Crowder


You can create a closure.

div.onmouseover = function(){ handler(arguments,here); }
like image 38
Josh Avatar answered Feb 21 '26 18:02

Josh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!