This is regarding the mentioned methods of sap.ui.model.json.JSONModel in SAPUI5:
setJSONsetDataloadData
What is the difference between these 3 methods? When do we use these methods and can we use more than 1 of them for the same purpose?
On
setData
You have a JavaScript object and want to use this data as your model
const oJSONData = {
data: {
id: 4,
first_name: "Eve",
last_name: "Holt",
avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg"
}
};
oJSONModel.setData(oData);
setJSON
You have a String that when parsed represents a JavaScript object and want to use this data as your model
const sJSONData = '{"data":{"id":4,"first_name":"Eve","last_name":"Holt","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg"}}';
oJSONModel.setJSON(sJSONData);
loadData
You want to access a remote API which returns data as JSON and want to use this data as your model
const sURL = "https://reqres.in/api/users/4";
oJSONModel.loadData(sURL);
On
Luckily, the source code of UI5 is quite readable and often the better documentation than most of the API descriptions. Here is what each one of the APIs does basically:
"Parse the JSON text and call setData"
JSONModel.prototype.setJSON = function(sJSON, bMerge) { var oJSONData; try { oJSONData = jQuery.parseJSON(sJSON); this.setData(oJSONData, bMerge); } catch (e) { // ... } };
"Store the data and notify all dependent bindings (checkUpdate)"
JSONModel.prototype.setData = function(oData/*plain JS object*/, bMerge){ if (bMerge) { this.oData = /* merge with existing data */; } else { this.oData = oData; } // ... this.checkUpdate(); // notifies dependent bindings };
"Load data from the given remote URL and call setData" --> Please check the source here.
setData at some point.Which API to call in which situation depends on in which format you have the data available.
setJSONloadDatasetData
Have a look at the well documented API Reference for
JSONModel.In summary (from SAP Documentation):
setData: Sets the data, passed as a JS object tree, to the model.e.g
loadData: Load JSON-encoded data from the server using a GET HTTP request and store the resulting JSON data in the model. Note: Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy, the request can not successfully retrieve data from a different domain, subdomain, or protocol.e.g. you can use this to load/GET changes to the data/model and automatically updates the view if that specific model has being binded by reloading the url. If you use load, you don't need the other two in my opinion and
loadDatawith not work on local json data.setJSON: Sets the data, passed as a string in JSON format, to the model.i.e. Same as Set Data but strict JSON