0

I'm trying to store an object of selectors in jQuery for performance reasons and later use.

In some case, I may need to access a key in the same object literal I am creating.

(function($) {

    'use strict';

    var appCache = {

        $navSecondary: $('#nav-secondary'),
        $navMore: appCache.$navSecondary.find('.more')

    };

})(jQuery);

The above code produces the error:

TypeError: appCache is undefined

how can I get around this? Would I have to perform the selection again in jQuery?

Thanks.

1
  • 1
    When you call appCache to set $navMore, appCache is still undefined. Commented May 19, 2014 at 16:30

3 Answers 3

4

The right hand side of the assignment operator is evaluated first. The result is then passed left and assigned to the variable.

The variable is undefined while the object is being constructed, so you can't use its value (it has been declared though, var statements are hoisted).

You can assign a new property after the object has been created.

var appCache = {
    $navSecondary: $('#nav-secondary')
};
appCache["$navMore"] = appCache.$navSecondary.find('.more');
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for explaining why the above approach does not work and offering a solution at the same time.
1
 var appCache = {

    $navSecondary: $('#nav-secondary'),
    $navMore: appCache.$navSecondary.find('.more')
              ^^^^^^^^

};

Because you are trying to access variable during its initialization.

Comments

1

You could use a function instead:

$navMore: function(){return this.$navSecondary.find('.more')}

Then call it once object is initialized:

appCache.$navMore(); // this will return set of jQuery matched elements

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.