Thursday, July 21, 2016

OpenUI5 DataBinding and setModel(model) vs setModel(model, "myModel")

The data binding has been driving me crazy and I wasn't able to find an explanation of the different syntaxes used in many of the examples I've seen.

var model = new JSONModel({
   "isValid" : true
});

If I do this.getView().setModel(model), how is that different from this.getView().setModel(model, "myModel")?   How do I reference them from the xml view definition?

The setModel(model) version

When you do this.getView().setModel(model) it actually sets the data into the model in an "undefined" area of the model.  (Check in the browser debugger).   So when you reference it in the xml view, you use a system like:

<Text text="{isValid}"/>

It appears if you try and set 2 models this way, one will not be set and will be unavailable.

The setModel(model, "myModel") version

When you do this.getView().setModel(model, "myModel) you are now seting the data into the model with the "myModel" name.   So if you look in the browser debugger it will be nicely nested inside the view's model data structure.  So now to reference it you use the ">" notation to tell it to grab the named model instead of the generic one.  So it looks like this:

<Text text = "{myModel>/isValid}"/>

If you are referencing array data like in a list or table, then you drop the / after the > to make it a relative reference:

<Text text = "{myModel>isValid}"/>