0

I am using the following code to add an event listener on a DOM element:

var me = this;

element.addEventListener('click', function(element) {
    return function(evt) { 
        me.handler(evt, element); 
    };
} (element) , false);

When I click the element, the handler is called with the event and the element as parameters.

I have read through the information about closures here, but I'm still not clear how the event object gets associated with the evt variable.

Community
  • 1
  • 1
  • There's a reasonable chance that the code will simplify to `element.addEventListener('click', this.handler, false);`. `evt` will be passed naturally to the handler, as the only parameter. Inside the handler, `this` will refer to the clicked element, so there's no need to pass it. – Beetroot-Beetroot Oct 17 '13 at 04:54
  • Regarding the code in the question, you won't find anything in the "closures" literature to explain `evt`. Only `element` is trapped in the closure. `evt` is the sole argument of a returned function, which becomes the click handler - as if you had attached the inner function directly, without the outer (closure-forming) function. – Beetroot-Beetroot Oct 17 '13 at 05:07

1 Answers1

1

Why don't you just use

var me = this;
element.addEventListener('click', function(evt) { 
     me.handler(evt, element); 
} , false);

I'm still not clear how the event object gets associated with the evt variable.

If you use addEventListener, when the event is fired, the event listener receives an argument which is the event.

Then, when you add your event listener, the following code

function(element) {
    return function(evt) { 
        me.handler(evt, element); 
    };
} (element)

is evaluated and returns the following function

function(evt) { 
    me.handler(evt, element); 
}

which is the event handler. Then, its first argument evt is the event.

Oriol
  • 274,082
  • 63
  • 437
  • 513