Javascript event handler with parameters -
i want make eventhandler passes event , parameters. problem function doesn't element. here example:
doclick = function(func){ var elem = .. // element elem.onclick = function(e){ func(e, elem); } } doclick(function(e, element){ // stuff element , event });
the 'elem' must defined outside of anonymous function. how can passed element use within anonymous function? there way this?
and addeventlistener? don't seem able pass event through addeventlistener @ ?
update
i seemed fix problem 'this'
doclick = function(func){ var = this; this.element.onclick = function(e){ func(e, that); } }
where contains this.element can access in function.
the addeventlistener
but i'm wondering addeventlistener:
function doclick(elem, func){ element.addeventlistener('click', func(event, elem), false); }
i don't understand code trying do, can make variables available in event handler using advantages of function closures:
function addclickhandler(elem, arg1, arg2) { elem.addeventlistener('click', function(e) { // in event handler function here, can directly refer // arg1 , arg2 parent function arguments }, false); }
depending upon exact coding situation, can pretty make sort of closure preserve access variables you.
from comments, if you're trying accomplish this:
element.addeventlistener('click', func(event, this.elements[i]))
then, self executing function (iife) captures arguments want in closure executes , returns actual event handler function:
element.addeventlistener('click', (function(passedinelement) { return function(e) {func(e, passedinelement); }; }) (this.elements[i]), false);
for more info on how iife works, see these other references:
javascript wrapping code inside anonymous function
immediately-invoked function expression (iife) in javascript - passing jquery
what use cases javascript self executing anonymous functions?
this last version perhaps easier see it's doing this:
// return our event handler while capturing argument in closure function handleevent(passedinelement) { return function(e) { func(e, passedinelement); }; } element.addeventlistener('click', handleevent(this.elements[i]));
it possible use .bind()
add arguments callback. arguments pass .bind()
prepended arguments callback have. so, this:
elem.addeventlistener(function(a1, a2, e) { // inside event handler, have access both arguments // , event object event handler passes }.bind(elem, arg1, arg2));
Comments
Post a Comment