Last active
March 30, 2016 21:44
-
-
Save pseudosavant/8720377 to your computer and use it in GitHub Desktop.
Automatically cache your DOM queries using a wrapper function like this.
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 wrapper | |
var cacheQuery = function(query) { | |
this.cache = this.cache || {}; | |
if (!this.cache[query]) { | |
this.cache[query] = jQuery(query); | |
} | |
return this.cache[query]; | |
}; | |
// DOM wrapper | |
var cacheQuery = function(query) { | |
this.cache = this.cache || {}; | |
if (!this.cache[query]) { | |
this.cache[query] = document.querySelectorAll(query); | |
} | |
return this.cache[query]; | |
}; | |
// Example | |
cacheQuery('.myForm input[type=submit]').val('Processing'); // Returns `DOMElement` or a jQuery object after a lookup | |
cacheQuery('.myForm input[type=submit]').attr('disabled', true); // Returns same `DOMElement` or jQuery object but without doing a lookup |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This piece of code can't work, I assume you nee to use the constructor.
Or maybe I'm looking at the wrong way, then please explain how 'this' could work according to your function?