Use the RootObject operator in a ViewModel expression or action when you need to inspect or update the object instance that opened the current ViewModel.
What RootObject returns
selfVM.RootObject returns the specific object instance used as the root when the current ViewModel was opened.
The root reference is read-only: while the ViewModel is open, you cannot change which object is its root. You can, however, change attributes on that root object.
For example, if the ViewModel was opened for a Thing object, RootObject refers to that particular Thing instance.
Check whether the ViewModel has a root
Use notEmpty to test whether the ViewModel is rooted in an object:
selfVM.RootObject->notEmpty
This expression evaluates whether a root object is present. Use it when an action or expression must behave differently for a rooted ViewModel.
Access attributes on the root object
RootObject is not typed as the model class that opened the ViewModel. Before accessing model-specific attributes or associations, cast it to the expected class with safeCast.
For example, to update SomeString on a root object that is a Thing:
selfVM.RootObject->safeCast(Thing).SomeString := 'a new value'
This changes the SomeString attribute of the existing root object. It does not replace the root object.
Why a cast is required
OCL is statically typed: OCL must know an expression's type before it can validate access to an attribute such as SomeString.
selfVM is context-sensitive and available in all ViewModels. Different ViewModels can be opened with different root classes, so there is no one model-class type that RootObject can always have. In the context of a specific ViewModel, you know the expected root class; use safeCast to state that type before accessing its members.
| Goal | Expression pattern | Example |
|---|---|---|
| Test for a root object | selfVM.RootObject->notEmpty
|
selfVM.RootObject->notEmpty
|
| Read or update a root-object member | Cast RootObject, then access the member | selfVM.RootObject->safeCast(Thing).SomeString := 'a new value'
|
Use RootObject in an action
- Identify the class that the ViewModel is expected to use as its root. In this example, it is
Thing. - Test
selfVM.RootObject->notEmptyif the action can run without a root object. - Cast RootObject with
selfVM.RootObject->safeCast(Thing). - Read or update the required attribute or association on the cast object.
Keep the cast aligned with the ViewModel's expected root class. A cast to an unrelated class does not give RootObject that class's attributes.
