Step 16: Dialogs and Fragments

介绍

In this step, we will take a closer look at another element which can be used to assemble views: the fragment.

1.练习效果

Step 16: Dialogs and Fragments - 第1张  | 优通SAP

2.源码

You can view and download all files at Walkthrough – Step 16.

webapp/view/HelloPanel.view.xml

We add a new button to the view to open the dialog. It simply calls an event handler function in the controller of the panel’s content view. We
will need the new id=”helloDialogButton” in Step 29: Integration Test with OPA.

It is a good practice to set a unique ID like helloWorldButton to key controls of your app so that can be identified
easily. If the attribute id is not specified, the OpenUI5 runtime generates unique but changing ID like __button23 for the
control. Inspect the DOM elements of your app in the browser to see the difference.

3.webapp/view/HelloDialog.fragment.xml (New)

We add a new XML file to declaratively define our dialog in a fragment. The fragment
assets are located in the core namespace, so we add an
xml namespace for it inside the
FragmentDefinition tag.

The syntax is similar to a view, but since fragments do not have a controller this attribute is missing. Also, the fragment does not have any footprint in
the DOM tree of the app, and there is no control instance of the fragment itself (only the contained controls). It is simply a container for a
set of reuse controls.

We also add an id for our Dialog to be able to access the dialog from our HelloPanel controller.

4.webapp/controller/HelloPanel.controller.js

If the dialog in the fragment does not exist yet, the fragment is instantiated by calling the sap.ui.xmlfragment
method with the following arguments:

  • The ID of the HelloPanel view

    This parameter is used to prefix the IDs inside our fragment. There, we have defined the ID helloDialog
    for the Dialog control, and we can access the dialog via the view by calling
    oView.byId(“helloDialog”). This makes sure that even if you instantiate the same fragment in other
    views in the same way, each dialog will have its unique ID that is concatenated from the view ID and the dialog ID.

    Using unique IDs is important, because duplicate IDs lead to errors in the framework.

  • The path of the fragment definition

We add the dialog as “dependent” on the view to be connected to the lifecycle of the view’s model. A convenient side-effect is that the
dialog will automatically be destroyed when the view is destroyed. Otherwise, we would have to destroy the dialog manually to free its
resources.

5. Conventions

  • Always use the addDependent method to connect the dialog to the lifecycle management and data binding of the view, even
    though it is not added to its UI tree.

  • Private functions and variables should always start with an underscore.

6.webapp/i18n/i18n.properties

We add a new text for the open button to the text bundle.

留下一个回复

你的email不会被公开。