Homelab, Linux, JS & ABAP (~˘▾˘)~
 

[SAPUI5] Model binding events

this.getView().bindElement({
				path: sObjectPath,
				events: {
					dataRequested: (oEvent) => {}, // Executed when a request to server is send
					dataReceived: (oEvent) => {},  // Executed when data from server is received
					change:(oEvent) => {},         // Executed everytime you do ElementBinding
				}
			})

The events for dataRequested and dataReceived are only fired, when data is requested or data is received from a backend. This is not the case, when the requested data is already available in the model from a previous backend call. In such situations, the change event comes in handy.

The same can also be done via XML:

binding="{
  path: '/myEntitySet',
  events: {
    dataRequested: 'onDataRequested',
    dataReceived: 'onDataReceived',
    change: 'onDataChange'
  }
}"

[SAPUI5] Get data of an Item of a List or Table

All options have in common that you first try to get the binding context from the list/table element via the event. Having the right context, you can either use the getProperty() function to get a specific property, or use the getObject() function to get all data.

onClick: function (oEvent) {
    // Option 1
    oEvent.getParameters().item.getBindingContext().getProperty("ID") 
    // Option 2
    oEvent.getParameters().item.getBindingContext().getObject().ID
    // Option 3
    oEvent.getParameter("item").getBindingContext().getObject().ID 
    // Option 4
    oEvent.getSource().getBindingContext().getObject().ID 
}

Note: When using a List, it’s oEvent.getParameters().listItem instead of oEvent.getParameters().item.

Or you could also use the sPath property from the binding context and directly get the data from the model.

onClick: function (oEvent) {
    // Option 5
    const sPath = oEvent.getSource().getBindingContext().sPath 
    // 5a
    this.getView().getModel().getProperty(sPath).ID 
    // 5b
    this.getView().getModel().getProperty(sPath + "/ID") 
}

[SAPUI5] Get and set properties of a binded model and submit changes

Get:

const oModel = this.getView().getModel()
const sPath = this.getView().getBindingContext().sPath
const sID = oModel.getProperty(sPath+"/ID")

Set:

const newID = "12345"
oModel.setProperty(sPath+"/ID", newID)

When using the set property function, you can now submit your changes this way:

        // First check if there are any changes    
        if (!oModel.hasPendingChanges()) {
           MessageToast.show("Nothing to do!")
           return
        }
        
        // Now submit your changes
        oModel.submitChanges({
          success: () => MessageToast.show("Success!"),
          error: (err) => alert(err)
        })

This way is much more comfortable, than using oModel.update().