-
-
Save jtsternberg/14978579a9edf42ed069 to your computer and use it in GitHub Desktop.
function Selector_Cache() { | |
var elementCache = {}; | |
var get_from_cache = function( selector, $ctxt, reset ) { | |
if ( 'boolean' === typeof $ctxt ) { | |
reset = $ctxt; | |
$ctxt = false; | |
} | |
var cacheKey = $ctxt ? $ctxt.selector + ' ' + selector : selector; | |
if ( undefined === elementCache[ cacheKey ] || reset ) { | |
elementCache[ cacheKey ] = $ctxt ? $ctxt.find( selector ) : jQuery( selector ); | |
} | |
return elementCache[ cacheKey ]; | |
}; | |
get_from_cache.elementCache = elementCache; | |
return get_from_cache; | |
} | |
var cache = new Selector_Cache(); | |
// get selector | |
cache( '#selector' ); | |
// get selector and reset cache | |
cache( '#selector', true ); | |
// get selector with $context | |
cache( 'img', cache( '#selector' ) ); | |
// get selector with $context, and reset | |
cache( 'img', cache( '#selector' ), true ); | |
// get selector with $context, and reset both selector and $context (whoa) | |
cache( 'img', cache( '#selector', true ), true ); | |
// Manually add a selector | |
cache.elementCache['#another-id'] = jQuery( document.getElementById( 'another-id' ) ); | |
// Then use it: | |
cache( '#another-id' ); |
First off, @jsternberg this is a very nice snippet. I would love to adopt this into my code, however... I'm having issues with resetting the cached selectors.
Here's my situation...
I have 3 JS files:
- File 1: Sets up the variables (caching all the repetitive selectors).
- File 2: Manipulates the HTML on the page, using the cached selectors from
File 1
. - File 3: Manipulates the manipulated HTML from
File 2
.
Basically each file relies on the file loaded before the current file is loaded.
By the time it gets to File 3
, I can't just use the cached selector variable from File 1
, I need to reset SOME of the cached selector variables from File 1
. inside of File 3
, because File 2
has made changes to them.
Specifying: cache( '#selector', true );
in File 3
doesn't appear to be working. I don't get any errors in the console. Just blank. So I'm not sure what's wrong with it, but it doesn't appear to be working as expected.
Just to clarify, the variable still works with what was cached in File 1
, BUT it hasn't been updated from the changes made in File 2
, when specifying cache( '#selector', true );
in File 3
.
I'm just using jQuery('#selector');
to target the modified selector for the time being.
It would be nice to be able to reset the cached selector.
I have the same problem as @bradyvercher. If context is a simple jQuery selector like $( '#container' )
then it's good. But if it's complicated like $( '#container' ).next()
then the code that retrieves context's key won't work reliably.
There is something wrong because calling to
cache( '#selector', true );
it fails with:Uncaught TypeError: $ctxt.find is not a function(…)
I think you can fix it setting
$ctxt = false
when $ctxt is typeof boolean in line 6.