JQuery: $ as parameter

I am reading a book on JavaScript explaining how to use the MVC pattern with JavaScript applications. This code shows how to configure the controller. Can someone explain why the jQuery dollar sign is passed as a function parameter in line 3, and then why there is 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);
+5
source share
3 answers

There is no dollar sign before jQueryin the last line, because the name of the variable that contains jQuery jQuery, rather than $jQuery. It went right away $to avoid name conflicts.

+6
source

Simply put, it does not guarantee that nothing will be named in this context $.

jQuery jQuery, $ , jQuery jQuery. $

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);
+2

jQuery, passed to the function, provides an argument to the $ function in the function. In other words, to ensure that the function understands that $ is a jQuery object, the full name of the jQuery object is passed instead of the name $ short. This helps in cases where other javascript libraries are used and can compete for the $ assignment.

+1
source

All Articles