Search code examples
sapui5sap-fiori

How can I destroy a View?


I would like to destroy a View and the corresponding Controller as soon as somebody is using the back button. This would give me the possibility to avoid a reset function and i could use user-created content within the init method from the new controller.

But the sap-ui-core is throwing an adding element with duplicate id error messages, what did i wrong?

var oView = sap.ui.view({
    id: id,
    viewName: "newController",
    type: sap.ui.core.mvc.ViewType.XML
})
oView.destroy();

oView = sap.ui.view({
    id: id,
    viewName: "newController",
    type: sap.ui.core.mvc.ViewType.XML
})
oView.destroy();

Solution

  • Old Answer - not recommended anymore

    i couldn't figure out, why these exceptions appear; independent from destroy() or deregister() calls.

    But if somebody trapped to into same problem. You can deactivate the DuplicatedIds check from the framework over the bootstrap as a temporal workaround.

    <script src="resources/sap-ui-core.js"
                    id="sap-ui-bootstrap"
                    data-sap-ui-libs="sap.ui.commons, sap.m"
                    data-sap-ui-theme="sap_bluecrystal"
                    data-sap-ui-noDuplicateIds="false"
                    >
    </script>
    

    Update UI5 1.8x.xx

    A lot has changes, this bug was fixed a long time ago. Therefore i update the answer. BUT Views/Controller are handled now by the router

    if you need this, you don't follow best practise.

    sap.ui.controller("view1.initial", { });
    
    var oView = sap.ui.xmlview("a", { viewContent: jQuery("#view1").html() } )
    oView.destroy();
    
    oView = sap.ui.xmlview("a", { viewContent: jQuery("#view1").html() } )
    oView.destroy();
    <script id="sap-ui-bootstrap"
    src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
    data-sap-ui-theme="sap_bluecrystal"
    data-sap-ui-xx-bindingSyntax="complex"
    data-sap-ui-compatVersion="edge"
    data-sap-ui-libs="sap.m"></script>
    
    <div id="uiArea"></div>
    
    <script id="view1" type="ui5/xmlview">
      <mvc:View controllerName="view1.initial" xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" > 
        <Button />
      </mvc:View>
    </script>