Reputation: 1196
I would like to make a JS function which handles its arguments independedently from where it is called. AFAIK the arguments differ, depending where the function is called.
Example 1
A commom usage is to register the function in HTML:
<input type="text" id="text1" onkeyup="myFunc(this);">
The element will then be passed on to the function:
function myfunc(element) {
alert(element.value);
}
Example 2
Another, appoach is to register it dynamically, when the document is finished loading. Something along those lines:
// init() gets called when document is ready
function init() {
document.getElementById('text2').addEventListener('keyup', myFunc2);
}
Now the function will receive an Event-Object instead of an Element-Object. I need to change the functions code to access the information.
function myFunc2(event) {
var element = event.target;
alert(element.value);
}
Example 3
One way to solve this problem would be to completely ingnore arguments and always gather all information inside the function, like this:
function myFunc3(event) {
var element = document.getElementById('text3');
alert(element.value);
}
The ugly thing about this solution is, that the GUI will be thigtly coupled to the logic.
Example 4?
One solution I can think of would be to change Solution 1 and pack the this
into an Event-Object? I have not tried this yet and I'm not sure how to do this most elegantly.
Ps: No JQuery "allowed"
Upvotes: 0
Views: 84
Reputation: 12796
The first one can be rewritten like this (note that it's preferred not to mix your markup with event handlers, however if you really want it to, then it can be written like this)
<input type="text" id="text1" onkeyup="myFunc(event);">
and the second one will take the input from the events target
property.
function myFunc(e) {
let element = e.target;
console.log( 'event comming from ' + element.id );
console.log( 'current value is ' + element.value );
}
window.addEventListener('load', function() {
let el = document.querySelector('#text2');
el.addEventListener('keyup', myFunc);
});
<input type="text" id="text1" onkeyup="myFunc(event);">
<input type="text" id="text2">
Upvotes: 1
Reputation: 596
You could have your function check the instance/type of the argument(s) and delegate the logic to other functions.
function myGeneralFunction(arg) {
if(arg instanceof Event) {
return handerForEvents(arg);
}
return otherHandler(arg);
}
Upvotes: 0
Reputation: 630
This covers both cases:
function foo(e) {
let element = e.target || e;
}
Upvotes: 1