Nir
Nir

Reputation: 25369

javascript event listener with param

I have a simple event listener:

function listen(evnt, elem, func) {
    if (elem.addEventListener)  // W3C DOM
        elem.addEventListener(evnt,func,false);
    else if (elem.attachEvent) { // IE DOM
         var r = elem.attachEvent("on"+evnt, func);
    return r;
    }
    return false;
}

I want to set listeners with a parameter. (the parameter is not set by the event, it is part of specific listener.

What I do and seems to work is:

function setlistener (param){

 listen ('custom event', document,
  function (e){
     run_func_with_param(param);
    }
  );
}

But I dont understand if its correct because param is not supposed to be defined when the event is fired.

My question is - is it the right way to have run_func_with_param called, each time with the params that was set for it in setlistener? In other words, is param remembered and will be set to the right values when run_func_with_param will be called as result of an event? (there will be multiple listeners with different params for the same event).

Notes: No jQuery/other libraries please. I'm using a custom event in this case.

Upvotes: 0

Views: 319

Answers (1)

jfriend00
jfriend00

Reputation: 707376

When you use an anonymous function, the arguments and local variables from the parent scope are still available in the anonymous function.

Thus, your argument named param is available inside your anonymous function that is passed to listen(). It isn't passed to that function - it's just available directly from the parent scope.

Here's your function with some annotation in comments:

function setlistener (param){
    // param is available here as an argument to setlistener
    // as a normal function argument
    listen ('custom event', document, function (e) {
        // param is still available here directly from the parent scope
        //     in this anonymous function.
        // This is one advantage of using anonymous functions.
        if (e.data.back_button==false){
          run_func_with_param(param);
        }
    });
}

Upvotes: 1

Related Questions