Created
February 12, 2009 04:29
-
-
Save jed/62488 to your computer and use it in GitHub Desktop.
A lightweight jQuery memoizer for caching the results of expensive DOM operations.
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
// jQuery.fn.cacheOf - By Jed Schmidt (MIT Licensed) | |
// A lightweight jQuery memoizer for caching the results of expensive DOM operations. | |
// Example usage: | |
// Say you have a processing-intensive call | |
// that occurs often in your code. | |
$().find( "*:not(:contains(abc))" ); | |
// Just initialize cacheOf with the method(s) | |
// for which results should be cached. | |
$.fn.cacheOf("find"); | |
// Then make the same call, but inject the cacheOf | |
// method to fetch the results and cache them. | |
$().cacheOf().find( "*:not(:contains(abc))" ); | |
// The next time you make the same call, the results | |
// will be pulled from cache instead of from the DOM. | |
$().cacheOf().find( "*:not(:contains(abc))" ); | |
// You can cache whatever methods you want. | |
// Just use spaces to separate each one. | |
$.fn.cacheOf("find offset myFunc"); | |
// Arguments are automatically hashed to memoize | |
// each unique call. | |
$("#myId").cacheOf().myFunc( 123, "abc", document.body ); | |
// jQuery's native data storage is used, so all | |
// cached values for a node are cleared upon removal. | |
$("#myId").data("cacheOf"); // => returns an object with all cache keys | |
// You can also expire a node's cache manually. | |
$("#myId").cacheOf( null ); | |
// Questions? Find me at http://twitter.com/tr4nslator. | |
jQuery.fn.cacheOf = ( function() { | |
var methods; | |
return function() { | |
if ( this.length === undefined ) | |
return methods = arguments[0].split(" "); | |
if ( arguments.length ) | |
return this.removeData( "cacheOf" ); | |
var ret = {}, cache = this.data( "cacheOf" ); | |
if ( !cache ) | |
this.data( "cacheOf", cache = {} ); | |
for ( var i in methods ) | |
ret[ methods[i] ] = bind( this, methods[i] ); | |
return ret; | |
function bind( context, name ) { | |
return function() { | |
var key = hash( [].concat.apply( [ name ], arguments ) ); | |
return cache[ key ] === undefined | |
? cache[ key ] = jQuery.fn[ name ].apply( context, arguments ) | |
: cache[ key ]; | |
}; | |
}; | |
function hash( items ) { | |
return jQuery.map( items, function( x ) { | |
return x.nodeType ? jQuery.data( x ) : x; | |
}).join(); | |
}; | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment