By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,385 Members | 1,767 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,385 IT Pros & Developers. It's quick & easy.

Passing values to callbacks

P: n/a
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){s omeClick(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"?
Jul 26 '08 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Phil wrote:
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){s omeClick(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
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <http://www.vortex-webdesign.com/help/hidesource.htm>
Jul 26 '08 #2

P: n/a
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){s omeClick(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){s omeClick(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
--
http://photo.gregorkofler.at ::: Landschafts- und Reisefotografie
http://web.gregorkofler.com ::: meine JS-Spielwiese
http://www.image2d.com ::: Bildagentur für den alpinen Raum
Jul 26 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.