0

What am I doing wrong here ???

var menu = {
    menuset : {
        first  : false,
        second : false,
        third  : false
    },
    setMenus   : function (selected) {

        var menuCollection = this.menuset;

        $.each(menuCollection, function (key, element) {
            if (selected===key) {
                key=true;
            } else {
                key=false;
            }
        });
    }
}

When I execute "menu.setMenus(first)" I want it to set the object like this :

    menuset : {
        first  : true,
        second : false,
        third  : false
    }

should I be using something other than $.each() ??

2
  • I don't understand why you have to use each in this case. Your setMenus function could be like this: this.menuset[ selected ] = true; (assuming you did all the modifications proposed by Jayendra) Commented Oct 23, 2011 at 18:51
  • Luiz think of this as a menu where only one navigation item is "active" hence the loop. Commented Oct 23, 2011 at 18:57

4 Answers 4

2

try -

var menu = {
    menuset : {
        'first'  : false,
        'second' : false,
        'third'  : false
    },
    setMenus   : function (selected) {

        var menuCollection = this.menuset;

        $.each(menuCollection, function (key, element) {
            if (selected === key) {
                menuCollection[key] = true;
            } else {
                menuCollection[key] = false;
            }
        });
    }
}

menu.setMenus('first');

Demo - http://jsfiddle.net/nu9v2/

Sign up to request clarification or add additional context in comments.

Comments

1

A couple of things:

  1. first is a property of this.menuset, but you are passing it just as first.
  2. The first arg to the callback fn for $.each is an integer index, but you are passing in a boolean.

Comments

1

You don't need jQuery

var menu = {
    menuset : {
        'first'  : false,
        'second' : false,
        'third'  : false
    },
    setMenus   : function (selected) {
        // set other values to false
        var keys = Object.keys(this.menuset);
        for (var i = 0, len = keys.length; i < len; i++) {
            this.menuset[keys[i]] = false;
        }
        // set correct value to true
        this.menuset[selected] = true;
    }
}

Example

1 Comment

But if you set another menuset to true both will be true, i think the op's intent is only for ONE menuset to be true, hence the loop.
0

should I be using something other than $.each() ??

I think map would be better here:

setMenus: function (selected) {
   this.menuset = $.map(this.menuset, function(val, key) { return key == selected })
}

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.