I'm reading a book on JavaScript that's explaining how to use the MVC pattern with JavaScript applications. In this code, it's showing how to set up a controller. Can anyone explain why the jQuery dollar sign is passed as a parameter to the function in line3, and then why there's no dollar sign in front of (jQuery) in the last line?
var Controller = {};
// Use a anonymous function to enscapulate scope
(Controller.users = function($){
var nameClick = function(){
/* ... */
};
// Attach event listeners on page load
$(function(){
$("#view .name").click(nameClick);
});
})(jQuery);
There's no dollar sign in front of jQuery
in the last line because the name of the variable that holds jQuery is jQuery
, not $jQuery
. It's passed immediately as $
to avoid naming conflicts.
Simply put, it's ensuring nothing else is named $
in that context.
The jQuery variable is named jQuery
, $
is a valid symbol in a variable name, and jQuery has used it to store the jQuery object. The code above could easily be rewritten to use any other variable name instead of $
var Controller = {};
// Use a anonymous function to enscapulate scope
(Controller.users = function(myJQueryVariable){
var nameClick = function(){
/* ... */
};
// Attach event listeners on page load
myJQueryVariable(function(){
myJQueryVariable("#view .name").click(nameClick);
});
})(jQuery);
The jQuery being passed to the function is supplying the argument for $ in the function. In other words, to guarantee that the function understands that $ is the jQuery object, the jQuery full object name is passed instead of the $ shortcut. This helps in cases where other javascript libraries are in use and might compete for the $ assignment.
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