DavidDecotigny

Blog-20070922212218-info

Navigation

  • Rechercher un mot :

Javascript partial evaluation


Sometimes, it's useful to create event handlers in javascript that call functions with some arguments pre-defined.
Example: I want to specify a "onclick" event handler on a DOM element 'foo' that will run myFunction(elt), with 'elt' being a given DOM element known when the event handler is declared. I cannot write:
foo.onclick = myFunction(elt);
Because myFunction will be executed when the event handler is assigned, not when the event is effectively fired (and, besides, the evaluation of myFunction will return probably 'undefined', not a function).
The partial.js? allows you to write:
foo.onclick = bindFunction(myFunction, elt);
The result of bindFunction is a function which will invoke myFunction(elt), it will be invoked when tyhe event is fired. You can also invoke object methods instead of calling functions:
foo.onclick = bindMethod(myObj, myObj.the_method, elt);
This code will invoke myObj.the_method(elt) when the event is fired.

This package is not limited to event handling, though I find it practical because it allows to specify event handlers when the javascript creates the DOM, with direct DOM element references instead of getElementById lookups. It also allows to specify a nice generic xmlhttprequest that just accept a callback() as argument, this callback being in fact a binding.

And the partial evaluation accepts any number of bound arguments, not just 1. And it's a real partial evaluation: if some arguments are not specified when the partial evaluation is created, the missing arguments will have to be specified when the resulting function is called:
function myFunction(a, b) { ... }
f = bindFunction(myFunction, 1); Partial evaluation
g = bindFunction(myFunction, 3, 4);
Complete parameter binding
Then:
f(2); Is equivalent to myFunction(1, 2)
g();
Is equivalent to myFunction(3, 4)