Vanquished Wombat
Vanquished Wombat

Reputation: 9525

An event to close any dialogue / fragment

In a fragment used as a dialogue it is common to have a cancel or close button wired with a press event. For example:

<buttons>
    <Button text="Save" press="onSaveData" type="Accept"/>
    <Button text="Cancel" press="onCancelBtn" type="Reject"/>
</buttons>

I have a couple of dialogues that appear in the current view I am working on. I would like to construct the onCancelBtn() event function to be generic, so have one close function into which the fragment is passed and closed - I assume the fragment is accessible from the event parameter, but how? Would .getView() not hit the main view?

Below is my current function but this refers to a specific dialogue.

    onCancelBtn: function(oEvent){
        this._oConfirmDialog.close();
    },

How do I use oEvent to get a reference to the fragment I want to close? If anyone can point me to documentation on the oEvent so I can read up on its structure I would be grateful. I got as far as the EventProvider in the API docs but lost the path there.

Upvotes: 1

Views: 11587

Answers (3)

Emil_1
Emil_1

Reputation: 11

I would reccomend using the following:

oEvent.getSource().getParent().close();

Upvotes: 0

Abhishek
Abhishek

Reputation: 43

There is a better and cleaner way to do this - write below code at the close event:

onClose: function(e) {
            e.getSource().destroy();
        }

Upvotes: 0

matbtt
matbtt

Reputation: 4231

A fully generic approach would be to traverse the control tree from the button which triggered the event to the top using methods getParent and getMetadata until you reach the containing dialog control you want to close.

Another approach I like better is the following one. Declare a custom data attribute containing the name of property holding the dialog instance at the cancel button and evaluate this attribute in a generic event handler.

  <Button data:name="MyDialog" text="Cancel" press="onCancelDialogPressed" type="Reject"/>

You can access this custom data attribute in the event handler:

onCancelDialogPressed : function(event) {
   var name = event.getSource().data("name");
   if (this.fragments[name]) {
       this.fragments[name].close();
   }
}

This works if you instantiate the dialog like this. You store the fragment under the name declared at the custom attribute.

openDialogPressed : function(event) {
   if (!this.fragments.MyDialog) {
        this.fragments.MyDialog = sap.ui.xmlfragment("..")
        this.getView().addDependent(this.fragments.MyDialog);
   }
   this.fragments.MyDialog.open();
}

Of course you need to declare fragments in your controller, e.g. in onInit:

this.fragments = {};

Upvotes: 2

Related Questions