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!
jQuery(selector). It's just using a closure to keep the cache in memory so it can look up the selector before querying the DOM.return cache[selector] || ( cache[selector] = jQuery (selector) );selector = 'div', how is that possible?();at the very end of the code snippet) and returns the second function, which is the one that takesselectoras an argument.