这样的事情可能很酷:
var _nodes = {};
var Module = {
/**
* You could call this when you want to query a selector and store it for reuse. Then
* just use this for querying.
*
* @param {String} selector The selector to memoize.
* @param forceUpdate {Boolean} jQuery selectors don't update with their DOM
* counterparts. This will take that into account. Pass in true to override cache.
*
* @return {Object<Array<jQuery>>} The matching selectors.
*/
$: function(selector, forceUpdate) {
if (forceUpdate === true || !({}).hasOwnProperty.call(_nodes, selector)) {
_nodes[selector] = jQuery(selector); // Not that robust, just a basic example
}
return _nodes[selector];
},
initialize: function() {
this.$('#form').submit(function () { /* ... */ });
}
};
So with this every time you query for a selector using the locally-scoped Module.$
function it would cache the result in the nodes object (which here is being exploited as an associative array). However if there was no result for that selector in the nodes object then it would query the DOM for it. Furthermore there's an added param to force the selectors in nodes
to be updated.
Alternatively you could use lodash's memoize function, like so:
// inside your Module
$: _.memoize(jQuery);