Errai: The browser as a platform

Monday, February 11, 2013

Style bindings

Yet another feature finds its way into the 3.0 branch today. And that feature is called style bindings; a feature designed to make your Errai UI-based apps even easier to work with.

When developing moderately-complex web applications with Errai, you may find yourself needing to do quite a bit of programmatic style changes. A common case being: showing or enabling controls only if a user has the necessary permissions to use them. One part of the problem is securing those features from being used, and the other part -- which is an important usability consideration -- is communicating that state to the user.

That's where style bindings come in.

Let's start with the example case I just described. We have a control that we only want to be visible if the user is an admin. So the first thing we do is create a style binding annotation.

That was pretty simple. All we did was create an annotation named Admin, and annotate it with the new @StyleBinding annotation.

This now means that @Admin is a style binding. Let's see how we can apply it.

Consider the following Errai UI template class

Here we have a contrived example of a button that deletes something. In this case, if the user is not an admin, which we're checking using a call to SessionManager.isAdmin(), we hide the button from view.

Although, we can potentially refactor this to reduce code re-use. If we're using the @Admin binding throughout our application, we can actually move the applyAdminStyling() method to a common location. Let's move it to the SessionManager.

When we remove that method from our Errai UI component, we get a far more elegant set of code:

Now, when we apply the @Admin rule to any Errai UI @DataField, we automatically inherit this functionality.

The additional bonus comes when using this in conjunction with Errai Databinding. Any Errai UI component which uses @AutoBound, will get live updating of the style rules for free, anytime the model changes. Allowing dynamic styling based on user input and other state changes.

As always, if you're interested, checkout Errai 3.0-SNAPSHOT if you're ready to try and get dirty with the latest and greatest features


  1. Whenever the data model changes, or if the widget state changes, or if you call StyleBindingRegistry.get().updateStyles(). This will all be properly documented soon. =)