Shaun Mccran

My digital playground

08
D
E
C
2010

Differences in calling a function in JQuery

I'm still playing around with some aspects of JQuery, and I noticed recently that I was still writing functions in the old school JavaScript fashion. I was constructing a JQuery selector, and then pointing the event handler to a separate JavaScript function. Like this:

view plain print about
1$("#type").change(changeFields);
2
3function changeFields(){
4    var selected = $("#type option:selected").val();
5            $('.formElems').hide();
6            $("." +selected).show();
7            }

I noticed then that all the other JQuery based functions do not construct the function as a separate entity. The function is embedded within the actual event handler.

More like this:

view plain print about
1$("#type").change(function ()
2        {
3        var selected = $("#type option:selected").val();
4            $('.formElems').hide();
5            $("." +selected).show();
6        });

Both methods work equally as well (IE they do what they are supposed to) but I can't see any reason you would do one over the other. The only thing I can think of is that in the first example the function is reference able from elsewhere, whereas the second code example is not.

Anyone more knowledgeable than me got a view on this?

TweetBacks
Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Steve Chandler's Gravatar As far as I can tell, your first method would be good for using "bind" and "unbind". You can bind changeFields to a specific element, then use unbind to remove that function only. It's a lot harder to unbind when using the latter.

http://api.jquery.com/unbind/
# Posted By Steve Chandler | 08/12/2010 14:57
Joel Stobart's Gravatar The first is re-usable but the second is more compact...
$("#type").change(function (){
   $('.formElems').hide();
   $("." +$("#type option:selected").val()).show();
}}
# Posted By Joel Stobart | 08/12/2010 15:11
Shaun McCran's Gravatar @steve, thats a good point on the 'bind' and 'unbind' functions. I'd never seen them before.

@Joel, I prefer the more compact version myself, I think unless there is a good reason to create a seperate function I'd use the shorter version.
# Posted By Shaun McCran | 08/12/2010 21:55
reflective tape's Gravatar The post is absolutely fantastic! Lots of great information and inspiration, both of which we all need! Also like to Logo design admire the time and effort you put into your blog and detailed information you offer! I will bookmark your blog and have my children check up here often.
# Posted By reflective tape | 13/01/2016 00:12
Back to top