Event for view leave

4.4k views Asked by At

I declared a controller for a view in my SAPUI5 application. Now I want to perform tasks when the view is left by the user.

There is already a possibility to add a callback function to attachRoutePatternMatched to perform tasks when the view is navigated by the user now I need a equivalent function to handle a leave of the view. I use a SplitContainer as parent container

onInit: function() {
  this._oRouter = this.getOwnerComponent().getRouter();
  this._oRouter.attachRoutePatternMatched(this._routePatternMatched, this);
},

_routePatternMatched: function(oEvent) {
  var that = this;
  var sRouteTargetName = oEvent.getParameter("name");
  if (sRouteTargetName === "myView") {
    // perform tasks if the view is opened by the user
  }
},
3

There are 3 answers

0
niceman On

You can try if this works:

navAway: function(viewName, callback) {
    this._oRouter.navTo(viewName);
    if(callback && typeof(callback) === "function") {
        callback();
    }
}

e.g. this.navAway("myView", function() { //doStuff });

0
hagen On

Presume you mean navigating backwards? If you have a back button, which presumably you must, put your actions in that function. E.g your detail/master has a navBack button in the toolbar, so put your logic in the button's event handler...

0
Boghyon Hoffmann On

You can achieve this with BeforeHide delegate on the NavContainer child which is often the view:

onInit: function() {
  this._navDelegate = { onBeforeHide: this.onBeforeLeave };
  this.getView()/*<-- navContainerChild*/.addEventDelegate(this._navDelegate, this);
},

onBeforeLeaving: function(event) {
  // ... do something
}, 

onExit: function() {
  // detach events, delegates, and references to avoid memory leak
  this.getView().removeEventDelegate(this._navDelegate);
  this._navDelegate = null;
},

Example: https://embed.plnkr.co/wp6yes?show=controller%2FNext.controller.js,preview%23next


For other navigation related events, see documentation topics mentioned in https://stackoverflow.com/a/55649563