How execute code every time that I view a page - sapui5

I'm searching the mode to execute a code (in my case the retrieve of data to visualize from server) every time I view a page (every time the page is called by splitApp.toDetail or splitApp.backDetail). How can i do it?
P.S. The onBeforeRendering and onAfterRendering execute only the first time.

There is a solution for you. There is a event called routeMatched when navigation is triggered every time. You can attach the event in the detail page.
onInit : function () {
this._oRouter = sap.ui.core.UIComponent.getRouterFor(this);
this._oRouter.attachRouteMatched(this.handleRouteMatched, this);
},
handleRouteMatched : function (evt) {
//Check whether is the detail page is matched.
if (evt.getParameter("name") !== "detail") {
return;
//You code here to run every time when your detail page is called.
}

I´m using onBeforeShow in my target views for that.
onBeforeShow : function(evt) {
// gets called everytime the user
// navigates to this view
},
This is a function which is fired by a NavContainer on its children in case of navigation. It´s documented in the NavContainerChild.

If routing is used, another version of Allen's code:
onInit : function () {
this._oRouter = sap.ui.core.UIComponent.getRouterFor(this);
this._oRouter.getRoute("detail").attachMatched(this.handleRouteMatched, this);
},
handleRouteMatched : function (evt) {
//You code here to run every time when your detail page is called.
}

Related

run controller function based on previous state name

I have an app with states including intro, account, etc..
I want to run openModal function in account controller only if previous state was intro.
How to do this?
Found a solution:
in app.js:
// recording previous state name
.run(function ($rootScope, $state) {
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState) {
$state.previous = fromState;
});
})
in controller:
$scope.$on('$ionicView.enter', function() {
if($state.previous.name=='intro')
$scope.showCardModal();
})
Listener in controller needed because in cached view ionic run controller only first time

Initializing input data

Where, and how do I clear out the input date on a view....
E.g. when the data is saved, and I access my page from the menu, the old data is still displayed in the input boxes.
I've tried the onInit() function but that only fires the first time into the view.
The navto call is in the BaseController which calls the defaultTimes page (view/controller).
onNavToDefaultTimes : function(oEvent) {
this.getRouter().navTo("defaultTimes");
}
My clear code was in the _onRouteMatched function of detaultTimes.....
_onRouteMatched : function(oEvent) {
var view = this.getView();
view.byId("shopInput").setValue("");
view.byId("effectiveDateFrom").setValue("");
view.byId("shop24Hrs").setSelected(false);
view.byId("shopClosed").setSelected(false);
},
The problem is though, _onRouteMatched is also callled from navBack of the page following default times. And I don't want to clear the fields in this case.
How do I implement the clear from the onNavToDefaultTimes function of the base Controller only?
Can you give an example.
Let's say the name of the view in which your input field is created is test.js, then whenever you are navigating to the view or navigating from the view, you can use invalidate view like below
sap.ui.getCore().byId("test").invalidate();
this makes the view to be rendered again when you are coming back to the view and onBeforeRendering() is triggered
You can choose one of the following options, and put one of them, after the code to save is executed:
Option 1:
var yourInput = this.getView().byId("yourInputID");
yourInput.setValue("");
Options 2 (Try someone):
var yourInput = this.getView().byId("yourInputID");
yourInput.unbindValue();
yourInput.unbindElement();
yourInput.unbindObject();
Or put the code in the following method, which is executed every time the view is displayed:
onAfterRendering: function(){
//Option choosed
}

sap.m.TileContainer scrollIntoView issue

I have an XML view that contains a TileContainer which is bound to a model that is used to create StandardTiles. The XML snippet is:
<TileContainer id="tilelist" tiles="{Applications}">
<tiles>
<StandardTile name="{ID}" icon="{Icon}" title="{Name}" press="doNavigation" info="{Description}"
number="{path : 'Number', formatter: 'linxas.com.fiori.launchpad.util.Formatter.formatUsingURL'}"
numberUnit="{NumberUnit}"/>
</tiles>
</TileContainer>
This is working perfectly, the correct tiles are getting displayed etc. When I click on a tile, there is navigation that occurs and I want to "remember" which tile was clicked (by index) so when returning I can scroll to that tile. This is done on the tile's press event handler (doNavigation function) and stores the index in sessionStorage. This is also working properly.
doNavigation : function (evt) {
if (sessionStorage && this.getView().byId('tilelist')) {
sessionStorage.setItem("selected_tile", this.getView().byId('tilelist').indexOfTile(evt.getSource()));
}
...
}
The proper value is stored. So when navigating back, within the onAfterRendering function of the page that contains the TileContainer I have the following code. It is attempting to see if there is a "selected_tile" value stored in sessionStorage, if so it calls scollIntoView passing in the tile index. The issue is that this code is executed, but doesn't work and I suspect it is because at the time of calling this function, the TileContainer's tiles aggregation is returning 0 length.
onAfterRendering : function (evt) {
var theList = this.getView().byId("tilelist");
if (sessionStorage && theList) {
var tile_index = sessionStorage.getItem("selected_tile");
console.log(tile_index + " of " + theList.getTiles().length);
if (tile_index) {
theList.scrollIntoView(+tile_index, true);
sessionStorage.removeItem("selected_tile");
}
}
}
My console output looks something like this (based on the tile that was clicked):
5 of 0
Any help would be appreciated. I assume that there is somewhere else that I need to execute this last bit of code as the TileContainer does not seem to be finished processing its tiles at this point, at least that is my assumption of why the tiles aggregation is 0.
Are you using Routing in your project?
If yes, you can try to register a method to handle the routePatternMatched event of the router. This method will be called after the onAfterRendering method - if the proper route pattern is matched.
To achieve this, just create the following:
onInit: function() {
sap.ui.core.UIComponent.getRouterFor(this).getRoute("NameOfYourCurrentRoute").attachPatternMatched(this._routePatternMatched, this);
},
_routePatternMatched: function(oEvent) {
//do your stuff here
},
Hopefully the TileList is ready at this point to navigate to the correct tile.

Event for view leave

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
}
},
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 });
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...
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
API reference: NavContainerChild
API reference: sap.ui.core.Element#addEventDelegate
For other navigation related events, see documentation topics mentioned in https://stackoverflow.com/a/55649563

Kendo layouts not rendering widgets without setTimeout

I upgraded the kendo library to the 2014Q1 framework which had a few nice features that they were adding, however when I did that it broke any widget (grid, tabStrip, select lists, etc.) from rendering at all. I tracked it down to the layout/view not being able to activate the widget without being wrapped in a setTimeout set to 0. Am I missing something key here or did I build this thing in an invalid way?
http://jsfiddle.net/upmFf/
The basic idea of the problem I am having is below (remove the comments and it works):
var router = new kendo.Router();
var mainLayout = new kendo.Layout($('#mainLayout').html());
var view = new kendo.View('sample', {
wrap: false,
model: kendo.observable({}),
init: function() {
// setTimeout(function(){
$("#datepicker").kendoDatePicker();
// }, 0);
}
});
mainLayout.render('#container');
router.route('/', function() {
mainLayout.showIn('#app', view);
});
router.start();
Admittedly, I don't fully understand it, but hope this helps.
Basically when you try to init the #datepicker, the view elements have not been inserted into the DOM yet. You can put a breakpoint inside the init function, when it hits, check the DOM and you will see that the #app is an empty div, and #datepicker does not exist yet (at least not on the DOM).
kendo.Layout.showIn seems to need to exit in order for the view to finish rendering, but when it initializes the view's elements, it thinks the render is done and init is triggered incorrectly ahead of time. The setTimeout works because it runs the kendoDatePicker initialization asynch, the view is able to finish rendering before the timeout function.
Workarounds...
Trigger the view rendering from the view object itself:
var view = new kendo.View('sample', {
init: function() {
$("#datepicker").kendoDatePicker();
}
});
router.route('/', function() {
view.render('#app');
});
Select and find the datepicker from the view object itself:
var view = new kendo.View('sample', {
init: function() {
view.element.find("#datepicker").kendoDatePicker();
}
});
router.route('/', function() {
mainLayout.showIn('#app', view);
});
Near the bottom of this thread is where I got the idea for the 2nd option. Maybe someone else can come around and give a better explanation of whats going on.