Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain: jQuery Caching Code

This snippet of code will return an element from a cache if it has been selected previously or select, cache, and return the element. It is useful for updating contents of elements which are never significantly changed (i.e, the parent of a counter seen by the user where the number changes but the parent does not). The code is as follows:

var $$ = (function() {
    var cache = {};
    return (function (selector) {
        return cache[selector] || ( cache[selector] = jQuery (selector) );
    });
})();

You can use it like so:

$$('#id')


Now... how the heck does this work? How does $$ have access to jQuery selector? It has nothing to do with $$ starting with $, you could just as well do var foo. How does $$ map what is passed into it to selector. I would expect to see var selector = argumentName inside of $$. Also, to me it does not appear that $$ is setup to receive arguments (e.g., function(input){} ) but it readily does?

This small piece of code is incredibly confusing to me and some clarity would be greatly appreciated. Thanks!

like image 892
Joshua Robinson Avatar asked Feb 16 '23 10:02

Joshua Robinson


1 Answers

It's pretty straightforward. Here is the equivalent code but in an unpacked version to make it more explicit:

function generateCachingJQuery() {
    var cache = {};
    function queryFunc(selector) {
        if (cache[selector]) {
            return cache[selector];
        } 
        else {
            cache[selector] = jQuery(selector); //same as $(selector)
            return cache[selector];
        }
    }
    return queryFunc;
}
var $$ = generateCachingJQuery();

If you notice, first you have an anonymous function - which I named generateCachingJQuery here - which returns the function that $$ ends up being. This is done so that nothing but the internal function (named queryFunc here) has access to the cache variable. The rest is just a one-liner which I unpacked here to make it more clear what it's doing.

EDIT: To be clear, $$ ends up being queryFunc in the above code, not generateCachingJQuery. Notice that queryFunc takes selector as a variable.

like image 160
Claudiu Avatar answered Feb 28 '23 05:02

Claudiu