Re: rookie question - let, scope, and callbacks

2012/5/25 Amy C <mathematical coffee gmail com>:
> Hi all,
> I've made myself a whole bunch of PopupSwitchMenuItems and tried to
> connect their 'toggled' callback to the same function, passing the
> name of the menu item as a parameter:
>    this._items = {};
>    this._toggleNames = {
>                         ignorePopups   : _('Ignore popups'),
>                         ignoreMaximised: _('Ignore maximised windows'),
>                         DEBUG: _('Debug mode')
>    };
>    for ( let propName in this._toggleNames ) {
>            this._items[propName] = new
> PopupMenu.PopupSwitchMenuItem(this._toggles[propName], false);
>            this._items[propName].connect('toggled', Lang.bind(this,
> function() { log(('toggled: ' + propName)); }));
>            // ... rest of code
>    }
> However when I toggle any of the items, I always get "toggled: DEBUG"
> as the output (this also occurs when I remove the Lang.bind, although
> I will eventually need it).
> Why is this happening? propName is only declared in the for statement,
> and I thought the use of 'let' made sure that `propName` didn't
> default to the last value that it had for the callbacks, i.e. DEBUG.

for (let v in somewhere)
translates to
let v;
for (v in somewhere)
so there is only one v shared by all callbacks. You need a new
variable in the body of the for loop if you want to capture different

(Yay for javascript scoping!)


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]