How-to save and share memory data in UI5

Tags: UI5, Fiori

When you want to save some variables at the client side, without using an OData Model connected to the backend, you can do it using a model of type JSON in your controller. Like you define objects using JSON, you can have a nested hierarchy. It's possible to set defaults of any type, and reference UI5 runtime variables.

// JSON Data Model to save and share variables
this._oModel = new sap.ui.model.json.JSONModel({
	editMode: false,
	displayMode: true,
	isDesktop: sap.ui.Device.system.desktop,
	isNoDesktop: !sap.ui.Device.system.desktop,
	shopCartId: "",
	defaultItem: [],
	attachmentBindingPath: "",
	user: {
		title: "",
		fullName: "",
		id: ""
	},
	countries: []
});

You can make the model available across the application in all controllers/views done in Component.js giving any name like "app":  this.setModel(this._oModel, "app");

After making it available across the application, you can reference it within XML Views, to bind control properties like enabled, to the model property,

<Button enabled="{app>/editMode}".../>

The property value can be changed: this._oModel.setProperty("/editMode", true); or readvar bEditMode = this._oModel.getProperty("/editMode");

See the API reference of JSON Model for more.