Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何创建jQuery元素缓存机制?_Javascript_Jquery_Oop_Dom_Caching - Fatal编程技术网

Javascript 如何创建jQuery元素缓存机制?

Javascript 如何创建jQuery元素缓存机制?,javascript,jquery,oop,dom,caching,Javascript,Jquery,Oop,Dom,Caching,我想我编写了一个简单的DOM缓存机制来提高效率,避免了多次调用,例如: if ($('foo').length) { $('foo').bar(); } 因此,我在我的项目主对象下创建了一个DomCache子对象: MyLib.DomCache = {}; 当我需要一个元素的jQuery对象时,我会在DomCache中查找,如果找到它,我就会使用它,否则我会创建它,然后将它放入DomCache对象中。我认为这将是一个很好的语法: MyLib.DomCache.foo = MyLib.

我想我编写了一个简单的DOM缓存机制来提高效率,避免了多次调用,例如:

if ($('foo').length) {
    $('foo').bar();
}
因此,我在我的项目主对象下创建了一个
DomCache
子对象:

MyLib.DomCache = {};
当我需要一个元素的jQuery对象时,我会在
DomCache
中查找,如果找到它,我就会使用它,否则我会创建它,然后将它放入
DomCache
对象中。我认为这将是一个很好的语法:

MyLib.DomCache.foo = MyLib.DomCache.foo || $('foo');
if (MyLib.DomCache.foo.length)
    MyLib.DomCache.foo.bar();
但是现在我认为
.get()
getter方法可能会更好:

MyLib.DomCache.get('foo').bar(); 
只是我不能实现!我不知道如何实现这种方法

// THIS IS THE QUESTION!
MyLib.DomCache.get = function(element){
    // TODO: If the passed `element` has been cached previously,
    // return it. If not, cache it in the MyLib.DomCache object and then return it.
};
有什么帮助/想法吗?

为什么有这么多东西?老实说,这个项目相当大,所以我想我必须将所有内容都封装在父对象中,以便更好地访问

嗯,这对我来说太复杂了。如果您担心额外的DOM查找,为什么不这样做呢

var $foo = $("foo");
if ($foo.length) {
    $foo.bar();
}

您可以使用现有的解决方案,或者将其用作灵感。例如


我知道你们在担心什么&不知怎么的,这让我想起了。

你们认为你们编写了一个简单的DOM缓存机制??它是复杂的还是荒谬的?当我不知道之前是否创建了$foo变量时,我认为大型js项目是必要的。它是复杂的还是荒谬的?我认为对于大型js项目来说,我不知道之前是否创建了$foo变量是必要的。
MyLib.DomCache = {
    pool: new Array(),
};

MyLib.DomCache.get = function(selector){
    if(this.pool[selector]){
        console.log('Existing element returns!'); // debug
        return this.pool[selector];
    }else{
        console.log('Element has been created & returned!'); // debug
        return this.pool[selector] = $(selector);
    }
};

// Test
if(MyLib.DomCache.get('#foo').length){
    MyLib.DomCache.get('#foo').bar();
}