Skip to content
Advertisement

How to use `oEvent` when loading fragment asynchronously?

I’m able to used oEvent when using this code:

onPressDialog: function(oEvent) {
    if (!this._oDialog) {
        this._oDialog= sap.ui.xmlfragment("idDialog", "com.Dialog", this);
        this.getView().addDependent(this._oDialog);
    }
    this._oDialog.setBindingContext(oEvent.getSource().getParent().getBindingContext());
    this._oDialog.open();
},

However, I’m trying to change it using Fragment.load but I’m not able to get the oEvent from the function. Any idea?

onPressDialog: function(oEvent) {
    if (!this._oDialog) {
        Fragment.load({ // Fragment required from "sap/ui/core/Fragment"
            id: this.getView().getId(),
            name: "com.Dialog",
            controller: this
        }).then(function(oDialog) {
            this.getView().addDependent(oDialog);
            oDialog.setBindingContext(/*Can't access the right oEvent values here*/);
            oDialog.open();
        }.bind(this));
    }
},

Advertisement

Answer

As explained in the linked answer above, the oEvent parameters are completely reset after the event handler (onPressDialog) is executed. I.e. after the fragment is fetched asynchronously, the oEvent object won’t contain the same references / parameter values anymore. Try storing the target reference in a closure variable before creating the fragment, and then use the variable when the promise is finally resolved.

Given <Dialog id="myDialog"> in the fragment definition:

Since UI5 1.93

Using the API oController.loadFragment

onPressDialog: async function(oEvent) {
  const myEventValue = oEvent.get/*...*/; // to use later without relying on oEvent
  const oDialog = this.byId("myDialog") || await this.loadFragment({ name: "com.Dialog" });
  // ... Do something with myEventValue ...
  oDialog.open();
},

Since UI5 1.58

Using the API Fragment.load

onPressDialog: async function(oEvent) {
  const myEventValue = oEvent.get/*...*/; // to use later without relying on oEvent
  let oDialog = this.byId("myDialog");
  if (!oDialog) {
    oDialog = await Fragment.load({ // Fragment required from "sap/ui/core/Fragment"
      id: this.getView().getId(),
      name: "com.Dialog",
      controller: this,
    });
    this.getView().addDependent(oDialog);
  }
  // ... Do something with myEventValue ...
  oDialog.open();
},
Advertisement