views:

43

answers:

3

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!

A: 

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();
}
ScottE
Is it complex or Ridiculous? I think it's necessary for big js projects when I donno whether I created that $foo variable before or not.
+1  A: 

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

Mike S
+4  A: 
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.

Sepehr Lajevardi