I have a callback that uses the event object to get a value and do stuff with it. I want to also pass the callback the value directly. There are many ways I can do this, but they all feel like bad code, here are a couple:
document.querySelector('div').onclick = log;
// Base Method Example
function log(event) { const id = event.target.id; console.log(id) } // Can't pass ID
// Wrapping
const execute = func => event => {
const id = event.id;
func.call(this, id);
}
document.querySelector('div').onclick = execute(log);
function log(id) { console.log(id) }
document.querySelector('div').onclick = log;
// Input type check
function log(input) {
const id = (input instanceof Event)? input.target.id : input;
console.log(id);
}
document.querySelector('div').onclick = log;
// Multiple inputs
function log(event, id) {
const input = event? event.target.id : id
console.log(input);
}
log(undefined, 42)
Of these, I'm leaning towards either wrapping or type checking, but is there an even more concise way of doing this? Are there any known best practices in terms of handling this requirement?