Reputation: 2491
I have a view which reprents the BreadCrumb of a website, I update the view by setting the crumbs like this
public void setCrumb(ArrayList<Crumb> crumbs) {
content.clear();
for (int i=0;i<crumbs.size()-1; i++){
Anchor anchor = new Anchor(crumbs.get(i).getText())
content.add(anchor);
content.add(new InlineHTML(" > "));
}
content.add(crumbs.get(crumbs.size()-1).getText());
}
Now, I want to add EventHandlers to every Anchor added. I could just set the handler in the for loop by doing something like anchor.addClickHandler(...)
but I'am using MVP, so the view doesn't have to manage handlers... I guess. In the presenter I have access to the panel that has all the anchors.
My question is : How to access the anchors from the presenter and set the eventHandler ?
Upvotes: 1
Views: 740
Reputation: 22899
In an MVP environment, creating of UI elements and catching events should happen in the View and the View should then handle those events and call to the Presenter to take appropriate action, like so:
public void setCrumb(ArrayList<Crumb> crumbs) {
content.clear();
for (int i=0;i<crumbs.size()-1; i++){
Anchor anchor = new Anchor(crumbs.get(i).getText());
anchor.addClickHandler(new ClickHandler(){
@Override
public void onClick(ClickEvent event) {
presenter.doSomethingAboutAnchorClicks(...);
}
});
content.add(anchor);
content.add(new InlineHTML(" > "));
}
content.add(crumbs.get(crumbs.size()-1).getText());
}
And in the Presenter, you want to have a method handleEvent(Event event)
that can consume the events, and a method that calls to the View to setCrumb(crumbs)
. It sounds to me like you're looking at MVP as the same as MVC. The difference is that handling events is the job of the Controller in MVC, while that job belongs to the View in MVP. There are some great resources out there on MVP, and you should definitely check them out. For basics, you can see the Wikipedia Article: Model-View-Presenter, which also contains references to several other great resources.
EDIT: here's some code from my personal use case, which is quite similar. This all happens in the View, based on a regionReportElement
provided by the Presenter.
private Map<String, Anchor> breadCrumbs = new TreeMap<String, Anchor>();
private Map<String, ReportElement> reportElements = new TreeMap<String, ReportElement>();
// .... other stuff ...
@Override
public void addReportElement(final ReportElement reportElement) {
Anchor anchor = new Anchor(reportElement.getShortName());
anchor.addClickHandler(new ClickHandler(){
@Override
public void onClick(ClickEvent event) {
presenter.onReportElementSelect(reportElement.getId());
}
});
reportElements.put(reportElement.getId(), reportElement);
if (breadCrumbs.get(reportElement.getId()) == null) {
breadCrumbs.put(reportElement.getId(), anchor);
if (breadCrumbs.size() > 0) {
breadCrumbContainer.add(new Label(" > "));
}
breadCrumbContainer.add(anchor);
}
}
// .... other stuff ...
Upvotes: 1