Reputation: 163
I'm working with some jquery that someone else wrote that looks like the following code and was wondering why the dollar sign should be passed to the javascript updateTextareas function.
It is using 2 arguments: $, $textareas. It seems to work fine with only one argument ($textareas).
I'm trying to figure out why the author would pass in the $ as the first argument in the updateTextareas function below:
( function($)
{
// why would the first argument ($) need to be passed here?
function updateTextareas($, $textareas)
{
$textareas.each(function()
{
alert($(this).val());
});
}
// document ready
$(function()
{
updateTextareas($, $('textarea.bio') );
});
} )(jQuery);
Upvotes: 2
Views: 1539
Reputation: 173572
At the point of function definition:
function updateTextareas($, $textareas)
The value of $
is already defined in the current scope (passed as an argument to the outer function), so passing it here again is completely useless and can be omitted.
Btw, it may have once been necessary when the function was defined outside of the (function($) { ... }(jQuery));
wrapper.
Upvotes: 3
Reputation: 44609
The idea is that this would allow you to pass a "façade" or another function who'll act like jQuery. This could be used in unit test for example.
But, honestly, that's a bit of an overhead and I wouldn't recommend doing so. It's mostly useless as is and there's easier way of achieving the same for unit test.
Upvotes: 0
Reputation: 32748
Its so that that code like this or other plugins can work with other Javascript libraries that might already be using the dollar-sign. In which case without flexible support for re-naming jQuery (basically) you'd have collisions.
Sure, the author could have originally not used $
at all and just used jQuery
everywhere and that would also skirt the whole issue - but the nice thing about using $
when you can is that its short and terse.
Upvotes: 1