JavaScript eventhandler: problem with execution of handler that got parameters
I have this problem:
I have defined an event handler which requires parameters on it.
var handler = function(p1, p2){
//some code
}
Then I add the event handler to an object insid开发者_StackOverflowe a function.
function foo(p1, p2){
//Some code
obj.addEventListener('click', handler(p1, p2), false)
}
As you already know the code above is not correct. It wont listen to the event. Instead it will execute the function instantly. Now to fix this I can just erase handler(p1, p2)
and insert function(){ handler(p1, p2) }
instead. But the problem is that I have an another function that I want to remove the event listener, which is not possible with the latter solution.
function koo(){
//Some code
obj.removeEventListener('click', handler, false)
}
How do I fix this?
I think you'll need to create a closure:
var createHandler = function(p1, p2){
return function (event) {
//some code that uses p1 and p2
};
};
var handler;
...and now you can assign the handler like so, while still having access to p1 and p2:
function foo(p1, p2){
handler = createHandler(p1, p2);
//Some code
obj.addEventListener('click', handler, false);
}
function koo(){
//Some code
obj.removeEventListener('click', handler, false);
handler = null;
}
Note that handler
is now a global variable.
Update: I just realized that in your case, this could be simplified by merging createHandler
and foo
as follows:
var handler; // we need this to be accessible both to foo and koo
function foo(p1, p2){
handler = function(event) {
// some code that uses p1 and p2
};
//Some code
obj.addEventListener('click', handler, false);
}
function koo(){
//Some code
obj.removeEventListener('click', handler, false);
handler = null;
}
I don't think you want to pass arguments there - because it is a callback, and you are never sure what those variables will be.
Can you do...
(function() {
var p1 = 'a',
p2 = 'b',
obj = document.getElementById('my-object');
var handleClick = function(event) {
// Access to p1 and p2
// Access to `event` object containing info about the event
}
obj.addEventListener('click', handleClick, false);
// If you want to remove it
obj.removeEventListener('click', handleClick, false);
})();
May I ask why you want to have arguments on it? Do you intend to call it from a non click triggered way as well?
Isn't it just this:
function foo(){
//Some code
obj.addEventListener('click', handler, false)
}
Pass the function instead of calling it.
精彩评论