[英]Passing around event object from event handler to some another function
Is it considered a bad practice to pass around event
object from an event handler to some another function. 将event
对象从事件处理程序传递到另一个函数是否被认为是不好的做法?
For example: 例如:
document.getElementById('something').addEventListener('mousedown', function(e) {
console.log(someAnotherFunction(e));
});
I don't know why, but to me this looks like a code smell ? 我不知道为什么,但是对我来说,这看起来像是代码的味道?
Generally no, that is a perfectly fine pattern. 通常不,那是一个非常好的模式。
It is a good idea, though, to decouple event handling and application logic. 但是,将事件处理和应用程序逻辑分离是一个好主意。 So instead of this: 所以代替这个:
document.getElementById('something').addEventListener('mousedown', doStuff);
function doStuff(event) {
var foo = event.target.getAttribute('foo');
console.log("doing stuff with " + foo);
doMagic(foo);
}
you would want to do that: 您想这样做:
document.getElementById('something').addEventListener('mousedown', function (event) {
var foo = event.target.getAttribute(foo);
doStuff(foo);
});
function doStuff(foo) {
console.log("doing stuff with " + foo);
doMagic(foo);
}
(Not sure if this applies in your case, consider this more of a general comment.) (不确定这是否适用于您的情况,请考虑一下此作为一般性评论。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.