myhandle.onclick = myfunction(param1,param2);
This is a common beginner error at a JavaScript level, and not something that libraries can really fix for you.
You are not assigning myfunction
as a click handler, you are calling myfunction
, with param1 and param2 as arguments, and assigning the return value of the function to onclick
. myfunction
doesn't return anything, so you'd be assigning undefined
to onclick
, which would have no effect..
What you mean is to assign a reference to myfunction
itself:
myhandle.onclick= myfunction;
To pass the function some extra arguments you have to make a closure containing their values, which is typically done with an anonymous inline function. It can take care of passing the event on too if you need (though either way you need a backup plan for IE where the event object isn't passed as an argument):
myhandle.onclick= function(event) {
myfunction(param1, param2, event);
};
In ECMAScript Fifth Edition, which will be the future version of JavaScript, you can write this even more easily:
myhandle.onclick= myfunction.bind(window, param1, param2);
(with window
being a dummy value for this
which you won't need in this case.)
However, since many of today's browsers do not support Fifth Edition, if you want to use this method you have to provide an implementation for older browsers. Some libraries do include one already; here is another standalone one.
if (!('bind' in Function.prototype)) {
Function.prototype.bind= function(owner) {
var that= this;
var args= Array.prototype.slice.call(arguments, 1);
return function() {
return that.apply(owner,
args.length===0? arguments : arguments.length===0? args :
args.concat(Array.prototype.slice.call(arguments, 0))
);
};
};
}