problem with simple iteration

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jezternz
    New Member
    • Jan 2008
    • 145

    problem with simple iteration

    Okay, so basicly I have an array of functions, these functions are used to setup different menu's.
    The very first function sets up the main menu and links to other menus/pages.
    Note I have written addEvent, and it is self explanatory and has been tested and works.

    Code:
    var buttons = ["MenuX", "MenuY", "MenuZ", "MenuZZ"];
    var menu_page_generators = [
    		function(m, mel){// Main Menu
    			for(var id=0;id<buttons.length;id++){
    				var t = document.createElement("div");
    				t.className = "menu-button";
    				t.appendChild(document.createTextNode("["+buttons[id]+"]"));
    				var func = function(){alert(id);};
    				addEvent(t, "click", func);
    				mel.appendChild(t);
    			}
    		},
    		function(m, mel){// ...
    			alert('hi2');
    		}
    	];
    So what this code should be doing is. It should create 4 buttons, each button named MenuX, MenuY, ect and when you click on button X it should alert "1", button Y should alert "2", ect

    Now to the problem. It names each of the buttons correctly, so the 'id' variable is obviously being applied correctly in the button creation lines. However when you click on the individual buttons they all alert '4'. So it is obvious that all the buttons are not taking the 'id' variable when the function is being created, but 'id' when the button is clicked (after the loop has completed and id=4).

    I do not understand why it is doing this? I would really like to get this fixed, any help would be much apreciated.

    Cheers, Josh
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    you unintentionally formed a Closure on line 8.

    to get out of this you can write the value to a property of the element and access that via this. (that’s the only thing I can remember right now)

    Comment

    • gits
      Recognized Expert Moderator Expert
      • May 2007
      • 5390

      #3
      i don't know whether the closure is unintentionally - it just closures the last value of id (it is an issue with for-loops) ... so when you create a 'real' or 'explicit' closure (like below) it should work:
      Code:
      var func = function(val) {
          return function() { alert(val) };
      }(id);
      kind regards

      Comment

      Working...