Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent multiple DOM searches in jquery

I created a function to return me a jquery element.

function GetDialogButton() {
    return $('a.dialog');
};

This was done as the same element was used within multiple other functions. I thought it best if it was obtained from a single place, therefore making it easier to change in future should the atribute name change.

I would like to improve this getter so that it does not perform a search everytime when called multiple times within a single page load.

How can I do this? do I cache it? or perhaps there is no need as this is optimised out?

like image 754
pingu Avatar asked Jun 21 '13 09:06

pingu


2 Answers

You can create a cache variable, but it will pollute the global namespace again

var dialogButton;
function GetDialogButton() {
    if(dialogButton){
        return dialogButton;
    }

    dialogButton = $('a.dialog');
    return dialogButton;
};
like image 188
Arun P Johny Avatar answered Nov 04 '22 23:11

Arun P Johny


Creating a global cache variable is not necessary. You can do it without adding a variable to the global scope. Something like this would do:

var GetDialogButton = (function() {
    var set;

    return function() {
        if (set === undefined) {
            set = $('a.dialog');
        }

        return set;
    };
}());
like image 2
lonesomeday Avatar answered Nov 04 '22 22:11

lonesomeday