When to use GWT ensureInjected()?
css, gwt
Solution
As Christian said, inside the UiBinder `ui.xml` file you don't have to worry about invoking `ensureInjected()`, the following XML statements do the job:
<ui:with field='myStyle' type='com...MyStyle'/>
<div class='{myStyle.redBorder}'/>
Of course this is assuming that there is somewhere a `MyStyle` interface defined:
public interface MyStyle {
public String redBorder();
}
Now I agree with you that things get annoying when you need to manipulate the `CssResource` extension outside of UiBinder templates. Precisely because you have to take care of invoking `ensureInjected()` somewhere before using the `MyStyle` instance with your widgets.
I personally use GIN to inject instances of extensions of `CssResource` whenever I need them.That way you can implement a custom GIN provider ensuring that `ensureInjected()` is called on the `CssResource` before injecting it. There are three steps involved there:
Create an interface for `MyStyle` alongside with a CSS file. MyStyle.java
public interface MyStyle {
public String redBorder();
}
MyStyle.css
.redBorder { border: 1px solid red; }
Expose it through a `ClientBundle` extension. Resources.java
public interface Resources extends ClientBundle {
@Source("MyStyle.css")
public MyStyle style();
}
Configure a GIN provider method to inject your instances of `MyStyle`. ClientModule.java
public class ClientModule extends AbstractGinModule {
@Override
protected void configure() {
//...
}
@Provides MyStyle createStyle(final Resources resources) {
MyStyle style = resources.style();
style.ensureInjected();
return style;
}
}
We smoothly inject the `Resources` instance here above, which means no more hassle of a static accessor calling `GWT.<Resources>create(Resources.class)` anywhere, it just all happens through the GIN injection.
Having done that you can inject your instances of `MyStyle` when you need them. For example (in some MVP context):
private Widget widget;
@Inject
public SomeView(final MyStyle style) {
//...
widget = uiBinder.createAndBindUi(this);
widget.addStyleName(style.redBorder());
}
Problem
I created a few styles into a CSSResource and it works well whether I use ``` GWT.<MyResources>create(MyResources.class).myStyles().ensureInjected(); ``` or not. Could anyone shed a light on this and explain when to use ensureInjected or not? Thank you! Daniel