9. DataBinding in View
Suppose we have a component like this:
<Title text="Hello {/recipient/firstName} {/recipient/lastName}" id="myControl123" />
and we want to change its value in code.
Do NOT do this:
var oTitle = this.getView().byId("myControl123");
oTitle.setText("Hello John Doe");
Do it like this:
<Title text="Hello {pageModel>/recipient/firstName} {pageModel>/recipient/lastName}" id="myControl123" />
this.getView().setProperty("/recipient", {
firstName: "Vasily",
lastName: "Pupkin"
});
Why?
Because these same data may be used by other components, and in that case, every time the data changes, you would have to select many components by ID and assign them new values.
With binding, the values are updated automatically.
And because it simplifies logic: all page state data will be described by a single JSON. This makes the code much easier to debug. This is the Data-Driven approach.
One-way and two-way binding
In the example above, we assigned a value to the model from JavaScript.
But the reverse process can also happen:
<Input value="{pageModel>/myinputvalue}" />
<Text text="{pageModel>/myinputvalue}" />
We have an input bound to a local model. So, every time the input content changes, the View writes the new value to the Model.
And the Text value will automatically update in RealTime without any extra code.
This two-way binding (when the View not only receives data but also sends data to the model) is only available if:
- The model is local (not oData)
- The binding expression has no complex processing. And only one value.
Binding expressions
You can bind multiple values together.
You can use a subset of JS (call methods, use ternary operators, concatenate strings).
You can use external formatter methods.
<Title text="Hello {/recipient/firstName} {/recipient/lastName}" id="myControl123" />
<Title text="{= ${/recipient/firstName} ? ${/recipient/firstName} : 'No Name' }" />
<Title text="{ path : '/recipient/firstName' , formatter : '.formatter.fomatName '}" />
<!-- where .formatter.fomatName is a method in the controller -->