4

How can I retrieve the View/Fragment a sap.ui.core.Control belongs to?

BR Chris

matbtt
  • 4,163
  • 17
  • 25
cschuff
  • 5,192
  • 3
  • 31
  • 51

2 Answers2

7

You can walk up the parents until you find the View. You should however not rely on identifiers. Use the Class or Metadata to identify a View:

  buttonPress: function(oEvent){
    var b = oEvent.getSource();
    while (b && b.getParent) {
      b = b.getParent();
      if (b instanceof sap.ui.core.mvc.View){
        console.log(b.getMetadata()); //you have found the view
        break;
      }
    }
  }

Example on JSBin.

Fragments are not added to the control tree. So you cannot find them. You can however find the view they have been added to.

schnoedel
  • 3,770
  • 1
  • 10
  • 16
4

If the identifier of your control contains the identifier of the View (something like "__xmlview42" if you are using XML views) you could extract it and call:

sap.ui.getCore().byId("__xmlview42")

to get the containing view. If the identifier is not present you can navigate through the control tree using:

control.getParent()

until you have a control whose identifier contains the View identifier. You could also navigate through the control tree until you reach the view.

For Fragments this won't work as the content will become part of the parent View.

matbtt
  • 4,163
  • 17
  • 25
  • hm... Views could still have a Component-prefix. Unfortunately controls in fragments do not seem to have any prefix, neither from the fragment nor from the dependen view... – cschuff Oct 19 '16 at 15:49