The following example is taken from GWT tutorial (http://code.google.com/webtoolkit/doc/latest/tutorial/codeclient.html):
private void addStock() {
final String symbol = newSymbolTextBox.getText().toUpperCase().trim();
newSymbolTextBox.setFocus(true);
if (!symbol.matches("^[0-9A-Z\\.]{1,10}$")) {
Window.alert("'" + symbol + "' is not a valid symbol.");
newSymbolTextBox.selectAll();
return;
}
if (stocks.contains(symbol)) {
newSymbolTextBox.selectAll();
return;
}
int row = stocksFlexTable.getRowCount();
stocks.add(symbol);
stocksFlexTable.setText(row, 0, symbol);
Button removeStockButton = new Button("x");
removeStockButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
int removedIndex = stocks.indexOf(symbol);
stocks.remove(removedIndex);
stocksFlexTable.removeRow(removedIndex+1);
}
});
stocksFlexTable.setWidget(row, 3, removeStockButton);
newSymbolTextBox.setText("");
refreshWatchList();
}
I have hard time understanding this: the clickhandler of removeStockButton is getting the index of the symbol and then removes from arrayList. How is the handler know dynamically about symbol? Because symbol is a variable define in the addstock method. During compile time or when the addStock() method is entered, symbol is known. But during run time when a button is clicked and the clickhandler code is entered now how does it know symbol it independent of addStock(). It is behaving like ruby generator. How does it work? Where is the magic here?
Thanks.