Applying dynamic arguments to JavaScript function but deferring invocation -


consider javascript code:

var somearg = "hello"; elem1.onclick = function() { foo(somearg); }; somearg = "bye"; elem2.onclick = function() { foo(somearg); }; 

i invoke foo argument "hello" when click on elem1, however, way above code works, foo invoked "bye" every time.

basically, i'd apply somearg foo not invoke foo until later.

the usual way builder function:

var somearg = "hello"; elem1.onclick = buildhandler(somearg); somearg = "bye"; elem2.onclick = buildhandler(somearg);  function buildhandler(arg) {     return function() { foo(arg); };; } 

...or function#bind:

var somearg = "hello"; elem1.onclick = foo.bind(null, somearg); somearg = "bye"; elem2.onclick = foo.bind(null, somearg); 

either way, you're doing creating new function that, when called, calls foo value pass it. reason original code doesn't work functions close on variable somearg, not value of when they're created. since use value when they're called, don't value want. both of solutions above (in different ways), create functions close on taking value of when function created instead.


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -