On Thu, Aug 18, 2011 at 10:41 AM, Jasper St. Pierre <jstpie...@mecheye.net> wrote: > On Thu, Aug 18, 2011 at 8:06 AM, Ole Ernst <oleer...@web.de> wrote: >> Hello everybody, >> >> I encountered a problem while writing a shell-extension. Based on a >> config-array (which gets loaded at start up) I want to create a variable >> number of PopupMenuItems, which should be connected to different functions. >> >> Here is the simplified code, which shows the unwanted behavior: >> http://pastebin.com/GsjzHVyK >> >> The problem is: no matter on what menu I click, the log always says >> Entry3 (last connected function). Actually I'd like it to show Entry1 to >> Entry3 based on the menu I click. >> >> Am I missing something? Is there another way of doing it? (Note: That's >> pretty much my first contact with javascript) > > JavaScript has funky scoping rules. > > First, make sure you use "const presets" or "let presets", otherwise > you're defining a global there. > > Second, the problem is that you're declaring "item" *outside* of the > for loop, which means that there's one variable which is updated per > loop, and all the closures reference the same variable. Putting "let > item;" inside the loop body should make it scoped to the block itself. > it is ok to "let item" outside the loop since "item = ..." will make "item" point to different variables each time.
I think the problem is which "key" the function get each time and the problem is the same with the following code: let set = {"a": 1, "b": 2, "c": 3}; let func = {}; for (let key in set) { func[key] = function() { print(key); } func[key](); } for (let key in set) { func[key](); } for (let ke in set) { let key = ke; func[key] = function() { print(key); } func[key](); } for (let key in set) { func[key](); } run it with gjs will print a b c c c c a b c a b c I think the problem is that you need to "let key" inside the loop. Somehow, in "for (let a in b)" a point to a same variable each time.~~~(afaik) >> Thanks in advance! >> >> Ole Ernst >> _______________________________________________ >> gnome-shell-list mailing list >> gnome-shell-list@gnome.org >> http://mail.gnome.org/mailman/listinfo/gnome-shell-list >> > > > > -- > Jasper > _______________________________________________ > gnome-shell-list mailing list > gnome-shell-list@gnome.org > http://mail.gnome.org/mailman/listinfo/gnome-shell-list > _______________________________________________ gnome-shell-list mailing list gnome-shell-list@gnome.org http://mail.gnome.org/mailman/listinfo/gnome-shell-list