Posts Tagged ‘parametros’

Javascript events & parameters

Monday, August 24th, 2009

Having learned the right way to register events to an object with javascript lead me to another couple of issues.
First I created a wrapper for the event handler so I might be able to manage both IE and FF, I based the wrapper on this.
The wrapper call ended like this:

addEvent(object,event,function);

The problem here was, what if the function parameter needs parameters??? I thought it was a big deal but after making a couple of Google searches I found that I could wrapp this function.

Let me put an example:

<script language=”javascript” type=”text/javascript”>
<!–
//an example function that doesn’t need parameters
function popAlert() {
alert(‘yadda yadda’);
}
addEventListener(obj,’click’,popAlert); //whenever obj gets clicked function popAlert will be executed

–>

</script>

This was no problem at all works perfect but there are some cases where the function called needs parameters. how could I do that?! I tried the following:

addEventListener(obj,’click’,popAlert(‘parameter’));

WRONG! didn’t work so I was like about to give up when I found I could do something like this:

addEventListener(obj,’click’,function(){popAlert(‘parameter’);});

This actually works so now I may pass parameters to any function I register to an event!

In the case I needed to pass an actual event the function would end up looking like this:

addEventListener(obj,’click’,function(e){doOnEvent(e);});

Note: This also applies for IE attachEvent.

Give it a try!