Search code examples
jquerywordpressobject-literal

$ for jQuery in object literals in Wordpress


I guess this might be a common question, however I can't find the answer.

I'm working on the structure of my JS for my custom Wordpress theme. I decided to use The Object Literal, because it seems to fit my goals the best and is easy to read.

For my functions that are included into the objects I want to use jQuery selectors with a $ symbol, but in order to do that I have to redefine var $ = jQuery; inside of each function which is an ugly solution. I can't use the global $ symbol because it's not assigned to avoid conflicts with other libraries. I'm not going to use any other libraries that use $ symbol, but some plugins might, so I would like to keep avoiding potential conflicts.

So my code looks something like this:

var myClass = {
    init: function() {
        var $ = jQuery,
            div = $('div');
        div.click(this.addMyClass);
        // And so on...
    },
    addMyClass: function() {
        var $ = jQuery;
        $('body').addClass('newClass');
        // And so on...
    }
}
jQuery(function($) {
    myClass.init();
});

Is there a way to avoid re-declaring $ for every function? Can I pass $ via init function? Like so:

var myClass = {
    init: function($) {
        var div = $('div');
        div.click(this.addMyClass($));
        // And so on...
    },
    addMyClass: function($) {
        $('body').addClass('newClass');
        // And so on...
    }
}
jQuery(function($) {
    myClass.init($);
});

Or is it a bad idea? Or maybe there's a better solution?


Solution

  • The best way is to use an IIFE that passes jQuery in as argument

    ;(function($){
     "use strict"; 
      // anywhere inside "$" is jQuery and is insulated from any other libraries
    
        var myClass = {
    
            init: function (){
                var div = $('div');        
                div.click(this.addMyClass);      
            }
        };
    
        $(function (){
            myClass.init();
        });
    
    })(jQuery);
    

    This also removes myClass from global namespace