DsDyer
DsDyer

Reputation: 83

Setting property values based on other properties of same object

Here is my code.

var myApp = {
    nav               : $('#top_nav .nav'),
    primary_navs      : $('#top_nav .nav').find('> li'),
    secondary_navs    : $('#top_nav .nav').find('> li').find('.secondary > li')
}

This works, but I would prefer not to repeat the jquery selector functions over and over. I would like to do,

    primary_navs      : nav.find('> li')

but this gives me "nav is not defined". I have tried myApp.nav, and this, but clearly neither works the way I think they should. How can I refer to properties of an object when defining new properties of the same object?

Upvotes: 0

Views: 108

Answers (4)

Paul
Paul

Reputation: 141827

You can create an object using new with an anonymous function:

var myApp = new function(){
    this.nav =  $('#top_nav .nav');
    this.primary_navs = this.nav.children('li');
    this.secondary_navs = this.primary_navs.find('.secondary > li')
};

Upvotes: 1

Jack
Jack

Reputation: 10993

All the statements when you are declaring the object are evaluated at the same time so you can't use the results of a previous attribute for a second. However what you can do is set your MyApp to equal a function that is immediately evaluated and returns an object.

For example

var myApp = function() {
   var $nav,  $primary_navs;   
   var $nav = $('#top_nav .nav');
   var $primary_navs = $nav.find('> li');
  return {
    nav: $nav,
    primary_navs:  $primary_navs,
    secondary_navs = $primary_navs.find('.secondary > li')
  }  
}();

Upvotes: 0

David Hellsing
David Hellsing

Reputation: 108500

You can encapsulate it into an anonymous function that executes and returns an object:

var myApp = (function($nav) {
    return {
        nav: $nav,
        primary_navs: $nav.find('> li'),
        secondary_navs: $nav.find('> li').find('.secondary > li')
    };
}($('#top_nav .nav')));

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55750

Cache the variable

var $nav = $('#top_nav .nav');

Then you can use it multiple times in your code

var $nav = $('#top_nav .nav'),
    $childrenLi = $nav.children('li');

var myApp = {
    nav               : $nav ,
    primary_navs      : $childrenLi ,
    secondary_navs    : $childrenLi.find('.secondary > li')
}

You can also use children to get the immediate children.

$('#top_nav .nav').find('> li') same as $('#top_nav .nav').children('li')

Upvotes: 4

Related Questions