Search code examples
javascriptfunctionaliasself-invoking-function

Why does my addEvent function need to be self-invoking?


I am teaching myself to code using javascript and one of the things that really got me excited was the ability to create a custom (shorter) version of addEventListener.

I have the following code:

var onEvent = function() {
 return function(obj, event, fn) {
   obj.addEventListener(event, fn, false);
 }; 
}();

onEvent(input,"keypress", pressedEnter);

(for my own personal usage i prefer using "When" rather than "onEvent".

After researching I think I understand that adding the () at the end of the function runs it. But why is this necessary? Won't the function run as soon as it's added to an object that will be clicked?

Similarly, I've created a shorter getElementById:

function grab(id) { 
 return document.getElementById(id); 
}

Why does this not need to run itself before being used? Am I misunderstanding the purpose of the ending parentheses?

Thank you.


Solution

  • var onEvent = function(obj, event, fn) {
      obj.addEventListener(event, fn, false);
    };
    

    Should do exactly the same.