I note that it's recommended to use named functions when binding an event handler to a javascript event. How can I do this when my function needs to be passed the this
object?
For example, how would I replace the anonymous function below by directly calling doFancyStuff
:
$(document).on('change', 'input.fancy-textbox', function () { doFancyStuff($(this)); }); function doFancyStuff($textbox) { // fanciness }
Extra points if you point out other conventions I might be breaking with the above code.
To clarify, I want to call the doFancyStuff()
method in my example from multiple places, otherwise yes, I could just do something like this:
$(document).on('change', 'input.fancy-textbox', doFancyStuff); function doFancyStuff() { var $textbox = $(this); // fanciness }
If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.
$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.
The this Keyword is a reference to DOM elements of invocation. We can call all DOM methods on it. $() is a jQuery constructor and in $(this), we are just passing this as a parameter so that we can use the jQuery function and methods.
I would say that's a matter of opinion. I see no problem using an anonymous function here. If this is the only place doFancyStuff
is called, you could do this:
$(document).on('change', 'input.fancy-textbox', doFancyStuff); function doFancyStuff() { // fanciness var $textbox = $(this) }
However, if this function is called from multiple places and you can't change the way it works, you would have to do something like this:
$(document).on('change', 'input.fancy-textbox', doFancyStuffFromEvent); function doFancyStuffFromEvent() { // fanciness doFancyStuff($(this)); } function doFancyStuff($textbox) { // fanciness }
Which is messy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With