从服务器获取异步数据后,我试图选择 CellTree 的第一个根节点。这是我的代码:
public class MyTreeModel implements TreeViewModel{
private MyServiceAsync myService = GWT.create(MyService.class);
public <T> NodeInfo<?> getNodeInfo(T value) {
Cell<MyTO> cell = new AbstractCell<MyTO>() {
@Override
public void render(Context context, MyTO value, SafeHtmlBuilder sb) {
//rendering node...
}
};
return new DefaultNodeInfo<MyTO>(value instanceof MyTO ?
createBranchDataProvider((MyTO)value) : //fetching child nodes
cerateRootDataProvider(), cell); //fetching root nodes
}
@Override
public boolean isLeaf(Object value) {
if (value instanceof MyTO) {
MyTO to = (MyTO)value;
return to.isLeafNode();
}
return false;
}
private AbstractDataProvider<MyTO> cerateRootDataProvider() {
AsyncDataProvider<MyTO> dataProvider = new AsyncDataProvider<MyTO>() {
@Override
protected void onRangeChanged(HasData<MyTO> display) {
AsyncCallback<List<MyTO>> callback = new AsyncCallback<List<MyTO>>() {
@Override
public void onSuccess(List<MyTO> result) {
updateRowCount(result.size(), true);
updateRowData(0, result);
}
@Override
public void onFailure(Throwable caught) {
Window.alert(caught.toString());
}
};
myService.getRootNodes(callback);
}
};
return dataProvider;
}
private AbstractDataProvider<MyTO> createBranchDataProvider(final MyTO value) {
AsyncDataProvider<MyTO> dataProvider = new AsyncDataProvider<MyTO>() {
@Override
protected void onRangeChanged(HasData<MyTO> display) {
AsyncCallback<List<MyTO>> callback = new AsyncCallback<List<MyTO>>() {
@Override
public void onSuccess(List<MyTO> result) {
updateRowCount(result.size(), true);
updateRowData(0, result);
}
@Override
public void onFailure(Throwable caught) {
Window.alert(caught.toString());
}
};
myService.getChildNodes(value.getId(), callback);
}
};
return dataProvider;
}
对于存储在客户端解决方案上的数据看起来很简单:我们可以调用类似
tree.getRootTreeNode().setChildOpen(0, true, true);
但是如果我们想异步获取数据,我们将捕获 IndexOutOfBoundsException 以防我们在创建树后立即尝试相同,因为尚未获取数据。我如何知道何时会在 cerateRootDataProvider() 中触发 onSuccess() 事件?或者我可以使用其他解决方案?请提出一些建议。