Passing values to callbacks

P

Phil

Consider the following code:

var pageEl=document. getElementById('someElement');
var foo='This is the right value of foo to use';
pageEl.addEventListener('click',function(evtObj){someClick(evtObj,foo);});
foo='This is the WRONG value of foo to use';

How do I get someClick to always use "the right value of foo"?
 
G

Gregor Kofler

Phil meinte:
Consider the following code:

var pageEl=document. getElementById('someElement');
var foo='This is the right value of foo to use';
pageEl.addEventListener('click',function(evtObj){someClick(evtObj,foo);});
foo='This is the WRONG value of foo to use';

How do I get someClick to always use "the right value of foo"?

pageEl.addEventListener('click',function(evtObj){someClick(evtObj,"This
is the right value of foo to use");});

Well, one could use a second variable, after all they are not *that*
expensive...

There's no "simple" solution for your "problem" (I frequently use
callbacks, but never had a comparable problem). When the callback
function gets invoked it uses the current value of foo - after all
that's the behaviour that - I suppose - all people (except you) want to
see. The normal situation looks more like this

var foo;
addListener(function() { callback(foo); });

to establish the closure and have a value assigned to foo later
somewhere else.

Gregor
 
T

Thomas 'PointedEars' Lahn

Phil said:
Consider the following code:

var pageEl=document. getElementById('someElement');
var foo='This is the right value of foo to use';
pageEl.addEventListener('click',function(evtObj){someClick(evtObj,foo);});
foo='This is the WRONG value of foo to use';

How do I get someClick to always use "the right value of foo"?

pageEl.addEventListener('click',
(function(s) {
return function(evtObj) {
someClick(evtObj, s);
};
})(foo),
false);

This has been asked here before.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,142
Messages
2,570,818
Members
47,362
Latest member
eitamoro

Latest Threads

Top