Magic Lasso
Magic Lasso

Reputation: 1542

javascript passing event in closure

I was trying the following:

f.addEventListener('submit',(function(frm){
var func = (function(e){somefunction(e,frm);})(e);
})(f),false);

But this is failing. I want to pass the form (f) as a static reference and the dynamic event object to the named function 'somefunction'.

What I have above isnt working, what is the right syntax for passing both?

Upvotes: 2

Views: 134

Answers (2)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123493

The issue is that each of the functions is being called right away, with undefined actually being passed to addEventListener().

You'll want to instead return one of the functions without its calling parenthesis so the event can call it later:

f.addEventListener('submit', (function (frm) {
    return function (e) {
        someFunction(e, frm);
    };
})(f), false);

Though, with event bindings, you may not necessarily need the closure, as the <form> will be the context (this) of the function passed:

f.addEventListener('submit', someFunction, false);

function someFunction(e) {
    var frm = this;
    // ...
}

Upvotes: 5

monastic-panic
monastic-panic

Reputation: 3997

not saure exactly what you are trying to do but, to looks like you are trying to manually pass in the form via the event handler. Instead save a reference and just refer to it in the handler such as

f.addEventListener('submit',function(){
    var func = function(e){
      somefunction(e,f);
    };
},false);

you shouldn't need the self executing functions unless I am missing your intent here

Upvotes: 1

Related Questions