I have the following code which is designed to create an onchange event handler for all elements with class name ‘State’. The only problem is that I want the element to be passed into the StateChange function. How can I update this JS to pass ‘this’ into the StateChange function?
var c = document.getElementsByClassName('State');
for (i = 0; i < c.length; i++) c[i].onchange = createEventHandler( StateChange, c[i] );
Edit: I forgot to provide the createEventHandler function. Sorry about that… Here it is:
function createEventHandler(fn, input) {
return function () {
fn(input);
};
}
Also, some clarification. The purpose of the function is to obviate the need to put the onchange event next to each element with class name = ‘State’. The result should be the same as if I were to write:
<select id="MyState1" class="State" onchange="StateChange(this)">
Update:
Re your updated question: You’ve said that the end result you want is as though you’d done this:
Your quoted
createEventHandlerfunction does exactly that.Original Answer(s):
I’m not entirely sure I know exactly what you’re trying to do. I can read the question at least two ways:
StateChangefunction call, you wantthisto refer to the element that changed.StateChangefunction call, you wantthisto be the same asthiswhere you’re setting up your event handler.Option 1: You want
this= element withinStateChangeYou don’t actually have to pass the element instance into
createEventHandler, because when the event occurs,thiswill refer to the element because of the way you’re hooking it up. But if you prefer to set it explicitly, yourcreateEventHandlerfunction could look like this:What that does is return a function that, when the event is triggered, will call the function you pass in (
StateChange) withthisset to theelementyou pass in.. This uses the JavaScriptcallfeature of function objects, which allows you to define whatthiswill be during the function call. You just pass it in as the first argument tocall(subsequent arguments are passed on to the function being called).If you want to rely on the fact that the way you’re setting up the handler,
thiswill already be set to the element instance, you can do away with theelementargument:That just passes along the
thisvalue set up for the event handler by the browser.Option 2: You want
this=thisas of where you’re setting up the handlerIt’s the same principle as the above, just with a different argument. In this case, you’ll need to pass
thisin:…and then
createEventHandlerlooks like this:(Note I’ve passed in the element as a second argument to
StateChange.)More reading:
this