user419746
user419746

Reputation:

How to create a jQuery element cache mechanism?

I think I wrote a simple DOM cache mechanism to be more efficient, avoiding multiple $('blah') calls, e.g.:

if ($('foo').length) {
    $('foo').bar();
}

So I created a DomCache child object under my project main object:

MyLib.DomCache = {};

When I need a jQuery object of an element, I look in the DomCache and if I found it I use it, elseway I'll create it and then place it into the DomCache object. I thought that this will be a good syntax for the purpose:

MyLib.DomCache.foo = MyLib.DomCache.foo || $('foo');
if (MyLib.DomCache.foo.length)
    MyLib.DomCache.foo.bar();

But now I think that a .get() getter method might work better:

MyLib.DomCache.get('foo').bar(); 

Simply I can't implement that! I have no idea how can I implement such a method!!

// 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.
};

Any help/idea?
Why so many objects? Honestly the project is pretty BIG and so I think I have to wrap everything in a parent object for a better polished access!

Upvotes: 2

Views: 2055

Answers (3)

sepehr
sepehr

Reputation: 18475

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();
}

I know what you're worry about & it reminds me of the Singleton Pattern somehow.

Upvotes: 0

Spain Train
Spain Train

Reputation: 6006

You could use an existing solution, or use it as inspiration. For example, http://plugins.jquery.com/project/jCacher.

Upvotes: 1

ScottE
ScottE

Reputation: 21630

Umm, this seems unnecessarily complex to me. If you're worried about an extra DOM lookup, why not something like this?

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

Upvotes: 0

Related Questions