I have the following code
void onSelectionChangedFiredSources( Event event, var detail,
SelectCheckboxMenuComponent target)
{
// getItemModels returns a list of objects
getItemModels( target.selectedItems )
..forEach( (item)
{
switch( item.label )
{
case 'Ear':
toggleDialog( 'paper-dialog-transition-center',
$['ear-side-dialog']);
break;
case 'Eye':
toggleDialog( 'paper-dialog-transition-center',
$['eye-side-dialog']);
break;
case 'Nostril':
toggleDialog( 'paper-dialog-transition-center',
$['nostril-side-dialog']);
break;
case 'Thorax':
toggleDialog( 'paper-dialog-transition-center',
$['thorax-side-dialog']);
break;
default:
srcDataMap.add( item.label, item.selected);
}
});
}
Run Code Online (Sandbox Code Playgroud)
When a case is triggered, I would like to break out of the foreach loop.
Note that each time the selection changes, all selections are return by the target.selectedItems expression. So if 'Ear' is the first selection, the loop is executed and when 'Eye' is then selected the list return will have both Ear and Eye. How is this best done? Thanks
You can't break a forEach call.
You can't use break because it's not a loop. It's a function call, and break only works inside the current function.
You can't return, because that just continues with the next element.
You can throw to end the forEach, but that's hardly pretty.
What you can do instead is to not use forEach at all, and use a for-in loop instead, and then break out of that using a labeled break:
void onSelectionChangedFiredSources(Event event, var detail,
SelectCheckboxMenuComponent target) {
// getItemModels returns a list of objects
var models = getItemModels(target.selectedItems);
loop: for (var item in models) {
switch (item.label) {
case 'Ear':
case 'Eye':
case 'Nostril':
case 'Thorax':
toggleDialog('paper-dialog-transition-center',
$['${item.label.toLowerCase()}-side-dialog']);
break loop;
default:
srcDataMap.add( item.label, item.selected);
}
}
}
Run Code Online (Sandbox Code Playgroud)
您需要使用标签,break因为没有标签只会破坏switch语句。
| 归档时间: |
|
| 查看次数: |
736 次 |
| 最近记录: |