views:

702

answers:

4

I'm aware that you can set an onclick handler like this:

my_a = document.createElement('a');
my_a.onclick = somefunction;

... but what if somefunction takes a parameter? For the sake of simplicity, let's say I need to pass it the string "x". Is is possible to dynamically set the onclick handler to somefunction('x')?

+2  A: 

You want to use what is called an anonymous function:

my_a.onclick = function() {
    somefunction(arguments, here);
};

If you want to retain "this" you can utilize closures:

my_a.onclick = function() {
    somefunction.call(my_a, arguments, here);
};
strager
+1  A: 

What you want is a partial function application:

function partial(func /*, 0..n args */) {
  var args = Array.prototype.slice.call(arguments).splice(1);
  return function() {
    var allArguments = args.concat(Array.prototype.slice.call(arguments));
    return func.apply(this, allArguments);
  };
}

Now, you will be able to do this:

my_a.onclick = partial(somefunction,1,2,3); //1,2,3 being some parameters
Andreas Grech
+2  A: 

Then you would create an anonymous function:

my_a = document.createElement('a');
my_a.onclick = function() { somefunction(x); };

If you also like to refer to this in somefunction, you could use a library like [Prototype][1], then you would do something like:

my_a = document.createElement('a');
my_a.onclick = somefunction.bind(this, x);

[1]: http://alternateidea.com/blog/articles/2007/7/18/javascript-scope-and-binding Blog article

bouke
A: 

The easiest way is to wrap it in an anonymous function. Like this:

my_a.onclick = function() { somefunction('x'); };

The downside is that "this" will no longer refer to "my_a" inside of the someFunction function, but if you don't need it to, then the anonymous function should work.

Matt Ephraim