-
Notifications
You must be signed in to change notification settings - Fork 104
Scopes
Alexander Casall edited this page Nov 3, 2015
·
20 revisions
Scopes are data-contexts which can be shared between multiple ViewModels. They reduce the complexity when you have to share information between ViewModels.
There are two types of Scopes:
- Global scopes which are Singletons, which can be used with the
@InjectViewModel
Annotation - Scopes that are related to an ID
public class PersonMasterViewModel implements ViewModel {
//Global Instance of the scope will be injected
//-> it doesn't matter in which ViewModel you do this -> you'll get the same instance
@InjectScope
private TestScope scope1;
private TestScope scope2;
private TestScope scope3;
PersonMasterViewModel(){
//get a scope for this ID. If it already exists in the storage you get it,
//if not, it get's created, stored in the storage and the `Scope` gets returned
scope2 = ScopeStorage.get(TestScope.class, "myId");
scope3 = ScopeStorage.get(TestScope.class, "myId");
}
#Examples
A good example are Master/Detail Views where you have ViewModels for Master and Detail. In this case you have to transport the information of the current selection from the Master-ViewModel to the Detail-ViewModel.
public class PersonMasterDetailScope implements Scope {
public ObjectProperty<Person> displayedPerson = new SimpleObjectProperty<>();
//Some logic which sets the displayed person - for example when the user chooses an element in the master list
...
}
public class PersonMasterViewModel implements ViewModel {
@InjectScope
private TestScope scope;
ObjectProperty<Person> selectedPerson = new SimpleObjectProperty<>();
public ScopedViewModelA() {
...
scope.displayedPerson.bind(selectedPerson);
...
}
}
public class PersonDetailViewModel implements ViewModel {
@InjectScope
private TestScope scope;
public ScopedViewModelB() {
scope.displayedPerson.addListener((b,o,newSelectedPerson)->initViewModelWithPerson(newSelectedPerson));
}
}