Created
July 15, 2010 16:58
-
-
Save cowboy/477204 to your computer and use it in GitHub Desktop.
jQuery memoization, of sorts. WIP UNTESTED
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* $imple cache - v0.3pre - 07/16/2010 | |
* http://benalman.com/ | |
* | |
* Copyright (c) 2010 "Cowboy" Ben Alman | |
* Dual licensed under the MIT and GPL licenses. | |
* http://benalman.com/about/license/ | |
*/ | |
(function($,window){ | |
'$:nomunge'; // Used by YUI compressor. | |
// Element cache. | |
var cache = {}, | |
// Element expando + unique ID for caching. | |
expando = '$implecache' + +new Date(), | |
guid = 0, | |
// A reference to the original method. | |
orig_init = $.fn.init; | |
$.fn.init = function( selector, context, use_cache ) { | |
var result, | |
key, | |
id; | |
// `context` arg wasn't passed, but `use_cache` was. | |
if ( typeof context === 'boolean' ) { | |
use_cache = context; | |
context = undefined; | |
} | |
// Use cache. | |
if ( typeof use_cache === 'boolean' ) { | |
// Generate a unique id from the passed selector and/or context. | |
key = $.trim( get_key( context ) + ' ' + get_key( selector ) ); | |
// If `use_cache` is true and the cache is populated, return that. | |
if ( use_cache && cache[ key ] ) { | |
return cache[ key ]; | |
} | |
} | |
// Call the original $.fn.init method with selector and context. | |
result = new orig_init( selector, context ); | |
// Since the cache is being used, update it for next time. | |
if ( key ) { | |
cache[ key ] = result; | |
} | |
return result; | |
}; | |
// This logic probably needs to be improved a bit. | |
function get_key( val ) { | |
var result, | |
id; | |
if ( val === undefined ) { | |
result = ''; | |
} else if ( typeof val === 'string' ) { | |
result = val; | |
} else if ( val && val.hasOwnProperty && val instanceof jQuery ) { | |
result = val.selector; | |
} else { | |
id = val[ expando ] || ( val[ expando ] = ++guid ); | |
result = expando + id; | |
} | |
return result; | |
}; | |
})(jQuery,this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment