Re: rookie question - let, scope, and callbacks
- From: Giovanni Campagna <scampa giovanni gmail com>
- To: Amy C <mathematical coffee gmail com>
- Cc: gnome-shell-list gnome org
- Subject: Re: rookie question - let, scope, and callbacks
- Date: Fri, 25 May 2012 22:41:32 +0200
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.
Unfortunately,
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
values.
(Yay for javascript scoping!)
Giovanni
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]