gpt4 book ai didi

javascript - 大规模 jQuery 选择器缓存

转载 作者:行者123 更新时间:2023-11-30 10:33:58 25 4
gpt4 key购买 nike

哪些模式可用于在大型 JavaScript 应用程序中缓存多个 jQuery 选择器以供重复使用?

关于将 jQuery 选择器存储在简单函数内的简单变量中已经有很多说法,但是在 JavaScript 对象中,例如在流行的模块模式中,如何干净地设置和存储它们?

我最初的尝试是使用全局变量,但这会弄脏命名空间并可能导致冲突。我的第二次尝试涉及将选择器存储在相应对象内的对象字面量中,但这会导致对它们的调用时间超过预期,例如:

var Module = {

nodes: {},

storeSelectorsInCache: function() {
Module.nodes = {
form: $('#form'),
grid: $('#grid')
};
},

initialize: function() {
Module.storeSelectorsInCache();

// notice the long hierarchy to get to Module.nodes.form
Module.nodes.form.submit(function() {
// event handler
});
}

};

一定有更简洁的速记方式。

最佳答案

像这样的东西可能很酷:

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 () { /* ... */ });
}
};

因此,每次您使用局部作用域的 Module.$ 函数查询选择器时,它都会将结果缓存在节点对象中(这里它被用作关联数组)。但是,如果在节点对象中没有该选择器的结果,那么它会查询 DOM。此外,还有一个附加参数来强制更新 nodes 中的选择器。

或者你可以使用 lodash 的 memoize函数,像这样:

// inside your Module
$: _.memoize(jQuery);

关于javascript - 大规模 jQuery 选择器缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15116934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com