Explain: jQuery caching code

This code fragment will return an element from the cache, if it was previously selected or selected, the cache and returns the element. It is useful for updating the contents of elements that have never been substantially changed (i.e., the parent element of the counter that the user sees where the number changes, but the parent element 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 this:

$$('#id')


Now ... how does it work? How does $$ have access to the jQuery selector? It has nothing to do with $$ , starting with $ , you can also make var foo . How $$ match what is passed into it on selector . I would expect to see var selector = argumentName inside $$ . Also, it seems to me that $$ configured to accept arguments (for example, function (input) {}), but does it easily do?

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

+4
source share
2 answers

It is pretty simple. Here is the equivalent code, but in the 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, you first have an anonymous function - which I called generateCachingJQuery here - which returns a function that ends with $$ . This is done so that nothing but the internal function (named queryFunc here) has access to the cache variable. The rest is just one liner that I unpacked here to make it clearer what it is doing.

EDIT: to be clear, $$ ends with queryFunc in the above code, not generateCachingJQuery . Note that queryFunc accepts selector as a variable.

+5
source
 var $$ = (function() { // begin closure var cache = {}; // keep in memory through closure // The function that gets assigned to `$$` return function(selector) { // If the element has already been queried (exists in the cache) // then return the element that was previously stored, // otherwise query the new element, add it to the cache and return it return cache[selector] || (cache[selector] = jQuery(selector)); }; })(); // end closure 
+3
source

Source: https://habr.com/ru/post/1499982/


All Articles