The following code will add only the last Widget in the loop to all the listener functions. All the functions will call toggleShow() on the last object.
Why does this happen, and is there a way to get each Widget object to be referenced in the corresponding function?
for each (var w:Widget in workspace.getWidgetList()) {
var widgetShow:NativeMenuItem = menu.addItem(new NativeMenuItem("Show " + w.title));
widgetShow.addEventListener(Event.SELECT, function():void {
w.toggleShow();
});
}
Make it a function, this happens because the loop runs to the end and w becomes the last element in that list so when the anonymous function is called it always uses the last element :