Skip to content

Instantly share code, notes, and snippets.

@jjeaton
Forked from jtsternberg/$-cache-with-find.js
Last active August 29, 2015 14:08
Show Gist options
  • Save jjeaton/c165b7bad8e0f83120fb to your computer and use it in GitHub Desktop.
Save jjeaton/c165b7bad8e0f83120fb 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; }
var cacheKey = $ctxt ? $ctxt.selector + ' ' + selector : selector;
if ( undefined === elementCache[ cacheKey ] || reset ) {
elementCache[ cacheKey ] = $ctxt ? $ctxt.find( selector ) : jQuery( selector );
}
return elementCache[ cacheKey ];
};
return get_from_cache;
}
var cache = new Selector_Cache();
// get selector
cache( '#selector' );
// get selector and reset cache
cache( '#selector', true );
// get selector with $ctxt
cache( 'img', cache( '#selector' ) );
// get selector with $ctxt, and reset
cache( 'img', cache( '#selector' ), true );
// get selector with $ctxt, and reset both selector and $ctxt (whoa)
cache( 'img', cache( '#selector', true ), true );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment