To explain we'll use the master detail snippet available in the data binding examples project. The snippet displays an SWT List filled with Persons. The Person model has one property, name. Upon selection in the List the name of the currently selected person is displayed in a Text widget.
The relevant data binding code is copied and pasted below...
// 1. Observe changes in selection.
IObservableValue selectionObservable = ViewersObservables
// 2. Observe the name property of the current selection.
IObservableValue detailObservable = BeansObservables
.observeDetailValue(Realm.getDefault(), selectionObservable, "name",
// 3. Bind the Text widget to the name detail (selection's name).
SWT.None), detailObservable, new BindSpec().setUpdateModel(false));
If you follow the comments in the snippet you'll see that we need to perform 3 steps:
- Observe changes of the viewer's selection.
- Observe the name property of the selection.
- Bind the text of the Text widget to the name detail (selected person's name).
1. Observe changes in the viewer's selection
IObservableValue has a value. I know, rocket science. But what IObservableValue provides us is a reference to a transient instance and we can observe changes from one instance to the next. If the selection of the viewer is a person the value of the selection observable will be this person. If the selection is null the value of the selection observable will be null. Regardless of the value we have a reference to an object that will contain the viewer's selection. Change events will fire when a new person, or null, is set as the value of this observable. This is the master.
2. Observe the detail of the master (name of the selected person)
When we observe a detail of the master we're effectively saying...
"observe the value of a property of the value contained in an observable".
Translated into our use case we're saying...
"observe the value of the name property of the person contained in the selection"
If the selection of the the Viewer is a Person with the name "mickey mouse" the following will be true...
- selectionObservable.getValue() == Person("mickey mouse")
- detailObservable.getValue() == "mickey mouse"
When the selection changes to a Person with the name of "daffy duck" the following will be true...
- selectionObservable.getValue() == Person("daffy duck")
- detailObservable.getValue() == "daffy duck"
When the selection changes to null the following will be true...
- selectionObservable.getValue() == null
- detailObservable.getValue() == null
When the master value changes the detail populates itself with the value from the master. This gives us the master detail behavior. To finish it off we need to...
3. Bind the detail to the Text widget
The last step is to bind the detail observable to the Text widget in order to display the detail. Enough said.
Tomorrow night I'll describe a use case that explains how this fits into using JFace Data Binding and the presentation model design pattern.