Databinding in GWT?
Silverlight has cool data binding. Given a data class in BlogPost.cs:
public class BlogPost {
public string Title {get; set;}
public string Author {get; set;}
public string Content {get; set;}
}
You can easily and declaratively add it to the UI in BlogView.xaml:
<StackPanel>
<TextBlock Text="{Title}" />
<TextBlock Text="{Author}" />
<TextBlock Text="{Content}" />
</StackPanel>
(Binding isn’t limited to strings - it’s a great deal more sophisticated.)
In the code behind in BlogView.xaml.cs:
public BlogView(BlogPost blogPost)
{
InitializeComponent();
DataContext = blogPost;
}
That’s it! We’ve told Silverlight where to pull UI elements from, and it takes care of the rest. We don’t have to write error-prone and difficult-to-test code that explicitly injects the values into the UI.
Because GWT is in Java, it has to be a bit clunkier. (No surprise there.)
Our pojo in BlogPost.java is heavier, because we need to write out getters and setters instead of using the syntactic sugar C# provides:
public class BlogPost {
private String title;
private String author;
private String content;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
From BlogView.ui.xml file:
<g:VerticalPanel>
<g:Label ui:field="title" />
<g:Label ui:field="author" />
<g:Label ui:field="content" />
</g:VerticalPanel>
In the code behind (BlogView.java), we have to explicitly wire it up:
@UiField Label title;
@UiField Label author;
@UiField Label content;
public BlogView(Blog blog) {
title.setText(blog.getTitle());
author.setText(blog.getAuthor());
content.setText(blog.getContent());
}
It doesn’t seem so bad here, because of how simple the example is. But with more complex apps where the data is more complicated, and it changes during the lifetime of the view, being able to be as declarative as possible is nice. Unit testing GWT can be a pain because the Java->JS compiler takes a while to run. With declarative data binding, there’s just less code to test.
(I would love to be more declarative in GWT. If anyone can enlighten me to any oversights, it’d be great.)
Of course, despite my gripes about GWT and Java, I’ll still use it over Silverlight because it compiles into super fast JavaScript, instead of asking my potential users to download Silverlight.
2 Notes/ Hide
-
likeipad2 liked this
-
miscarriage8it liked this
-
wtfnth posted this