0

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.

Nir
  • 24,619
  • 25
  • 81
  • 117
  • I think **param** will be viable for each event when it's fired. It's called closure. Better explained [here](http://stackoverflow.com/questions/12930272/javascript-closures-vs-anonymous-functions) – Ikrom Apr 14 '13 at 17:07

1 Answers1

1

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);
        }
    });
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Sorry but there is something that I dont understand. suppose I call setlistener(1), then I call setlistener(2). Does JS keep two instances of the anonymouse function, each with the parent scope that existed when they were declared? – Nir Apr 14 '13 at 18:41
  • @Nir - yes, javascript keeps each scope separately and all the variables in them. It's called a "closure". So each call to `setlistener()` will have it's own scope saved with it's own copy of `param` and that closure/scope will exist as long as it's still possible for the anonymous function callback to be called. – jfriend00 Apr 14 '13 at 18:48
  • Thanks jfriend00. thats what I was looking for. :-) – Nir Apr 14 '13 at 19:02