Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: passing $(this) to named function event handler

Tags:

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 } 
like image 657
ajbeaven Avatar asked Jan 26 '12 21:01

ajbeaven


People also ask

How do I pass data to event handler?

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.

What does $( this mean in jQuery?

$(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.

Why this is used in jQuery?

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.


1 Answers

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.

like image 95
James Montagne Avatar answered Sep 17 '22 17:09

James Montagne