Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: $ as a parameter

Tags:

jquery

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);
like image 658
Leahcim Avatar asked Sep 11 '12 18:09

Leahcim


3 Answers

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.

like image 154
Ry- Avatar answered Sep 22 '22 21:09

Ry-


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);
like image 26
CaffGeek Avatar answered Sep 23 '22 21:09

CaffGeek


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.

like image 27
davidethell Avatar answered Sep 24 '22 21:09

davidethell