Best practice to lazy load data on tab click - sapui5

Within the onBeforeRendering() function of a view how should I determine if a specific node is present in the model and modify the model to include the node if not? This question is about lazy loading of data to the model for data that will be infrequently accessed by users but would have a performance penalty if loaded with initial model data.
My use case has a list page leading to a detail page for whatever item in the list the use clicks. On the detail page is a set of tabs which expose sub-details related to the selected detail. Specifically a long text description of a the brief for a task.
The tab control leads via manifest.json style routing to display a view in the tabs content area.
This is my current working code which is within the onBeforeRendering event of the view controller:
onBeforeRendering: function(oEvent){
var sPath = this.getView().getBindingContext("Projects").getPath(); // something like /task/6
console.log('Path='+sPath)
var oModel = this.getView().getModel("Projects");
var oTask = oModel.getProperty(sPath + "/brief");
if (oTask) { // looks like /brief exists so must already have loaded the brief
// nothing to do
console.log('Use existing data')
}
else { // /brief not yet present so we need to load it up
console.log('Load new data')
oModel.setProperty(sPath + "/brief", "This is the brief...") // replace with loaddata() from server, use attachRequestCompleted to call function to modify model.
}}
Question - is this the correct approach?
Edit: Based on discussion in this question I modified my code to use an event that fires per display of the view. onBeforeRendering turned out to run without much apparent predictability - which I am sure it has but in any case I wanted a one-per-display event. Also, I fleshed out the code further but retained the basic structure and it appears to do what I wanted.

This is a valid approach. But you should think aboute following use case: What happens if the data you loaded have been changed at the backend? The JSONModel does not give you any support here as it acts dumb data store only.

Related

How to retrieve the rows which are selected in the list report page of smart templates

This is the List Report type of Smart Template application
Here I have selected 2nd and 5th row, I also have a button named Send Requests in the section part which is highlighted. If I click this button it calls a javascript controller function which is defined in the extensions of the application. In this js function how can I retrieve the selected rows that are selected?
I have enabled the checkboxes in this page by mentioning this code
"settings": { "gridTable": false, "multiSelect": true } in the manifest.json
As it was recommended by this link https://sapui5.netweaver.ondemand.com/#docs/guide/116b5d82e8c545e2a56e1b51b8b0a9bd.html
I want to know how can I retrieve the rows which got selected?
There is an API that you can use for your use case. It is described here: https://sapui5.netweaver.ondemand.com/#docs/guide/bd2994b69ef542998becbc69ab093f7e.html
Basically, you just need to call the getSelectedContexts method. Unfortunately you will not be able to really get the items themselves, only the binding contexts (which point to the data entities which are selected). Excerpt from the documentation:
After you have defined a view extension, you can access and modify the
properties of all UI elements defined within these extensions (for
example, change the visibility). However, you cannot access any UI
elements that are not defined within your view extensions.
In this type of table there is way.
var myTable=sap.ui.getCore().byId("your table id");
get all rows:
var myTableRows=myTable.getRows();
now get selected Indices
var selectedIndeices=myTable.getSelectedIndices(); //this will give you array of indeices.
now run loop on indeices array. And get particular row item;
// get binding path
var bindingpath=myTableRows[2].getBindingContext().sPath; // this will return eg:"/ProductCollection/2"
// now get Binding object of that particular row.
var myData=myTableRows[2].getModel().getObject(bindingpath); // this will return binding object at that perticular row.
// once your loop is over in the end you will have all object of selected row. then do whatever you want to do.
If you use smart template create an extension.
This is the standard event befor the table is rebinding:
onBeforeRebindTableExtension: function (oEvent) {
this._table = oEvent.getSource().getTable();
}
In your action function (or where you want) call the table and get the context :
this._table.getSelectedContexts();

Waiting for sap.ui.table.Table rendered after bound model has changed

I have sap.ui.table.Table which rows are bound to an JSONModel.
var oListModel = new sap.ui.model.json.JSONModel();
//oTable created here (sap.ui.table.Table)
oTable.setModel(oListModel);
oTable.bindRows("/");
When the table is rendered, i.e. the DOM is created for this table, i need to reference to the DOM to pass the DOM elements (table rows) to a library which will make them draggable.
My problem is: How do i know when the DOM for the table is created after the model has been changed and the table is rerendered? I didnt find any listener. The view controller's listener onAfterRendering() didn't help me.
The model is filled with data after a XMLHTTPRequest is successful. When i set the model in the success handler of the xht request and try to access the DOM elments directly afterwards they don't exist yet.
Thank you for your help!
You can add an event delegate
var oMyTable = new sap.ui.table.Table();
oMyTable.addEventDelegate({
onAfterRendering: function() {
$table = this.getDomRef() ....
}
});
a better way is to extend the control see Using addDelegate to extend a control to use third party functionality
UPDATE
the example in that blog doesn't work anymore fixed here
I had a similar issue recently where i had to access an element after a smartform (where the element is present) rendered onto the view. I posted my query here as well as my final solution (based on the accepted answer of #Dopedev). I am using XML views - including nested XML views - here however and the onAfterRendering didn't help for me as well.
I guess you could look at this solution - like it's mentioned in the accepted answer, it may not be an optimal solution, but it sure works. In my case there is not much of a performance issue with the binding of the DOMNodeInserted since it is being called in the onAfterRendering of the nested view that consists of only the smartform with an immediate unbinding upon finding.
The condition if (id === "yourtableid") { } should be enough to identify and pass on. Since you have a table and thus several child nodes, unbinding is imperative at this point.
Mutation Observer is the preferred method but i guess you may need to check the browser compatibility table at the end of the page to see if it matches your requirements. There is an example here. I have used Mutation Observer (outside of a SAPUI5/openUI5 environment) earlier and found it very convenient(and performant) to listen to DOM insert events. In fact the sap.ui.dt package consists of MutationObserver.js

SAPUI5 - Remove oData Model bound to view

I am new to SAPUI5 and I am very much in need of your help.
I have created an XML view and bound an OData model to it like below. Now all the controls in the view got bound and I am able to see the data.
this.getView().setModel(oModel);
Now I have a requirement in which I have to completely remove this binding from the view. I destroyed the oModel and removed all its bindings. And now when I refresh the view, the data still exists in the screen. I want all the data from the view to disappear.
oModel.destroy();
oModel.refresh();
this.getView().getModel().refresh(true);
I assume that you're using an sap.ui.model.odata.ODataModel to retrieve odata, then done binding using, for example, a JSON model, like so,
var oJson = new sap.ui.model.json.JSONModel({data : oData);
/* Here 'data' is any name that you provide to identify your data model,
'oData' is the data that is received as response from the sap.ui.model.odata.ODataModel */
And set this model to the view like you have mentioned,
this.getView().setModel();
Now, to remove this data from the view you can try the following,
oJson.setData({data : null}, true);
This would set the previously set oData to null and therefore all data binding from the controls in the view would be removed(changed to null).
I believe oJson.refresh() is optional, but you can try adding that as well if the change is not reflected.
Its an approach until may be you find something better :) Here is the documentation for the APIs that I've used.
If you are using
var dataModel = new sap.ui.model.json.JSONModel();
dataModel.setData(oDataResponse); //Data returned from oData.Read()
this.getView().setModel(dataModel, "dataModel");
Retrieve the model, Set the model to null, Update the binding
var dataModel = this.getView().getModel("dataModel");
if(dataModel){
dataModel.setData(null);
dataModel.updateBindings(true);
}

Router, model, or view, which one is the initiator

I am trying to be as lazy loading as possible,
But, I am puzzle on how to start, here is my "sequenced comprehension":
Objective: Create a contacts page with contacts existing on the server
Step1.0: To use the router: the <div id="contacts"> must exists to trigger a rule, so I stepped back to (Step0.9),
Step0.9: Created this div in the body. Fine, the router find the #contacts, Oh, but this is a view, ok, stepped back to (Step0.8).
Step0.8: Erase the div created in the body and replace it by a view instead:
contactsView = Backbone.View.extend
tagName: 'div',
id: 'contacts'
To be lazy loading, this view should only be created when the #contact is trigger in my router table, but I just removed it from by body, it does exist anymore, I am back to Step1.0 ???
Some tutorials found, shows global variable settings... Please, how the general scenario using a router, a view, their models, and collection should proceed (no code is necessary for an answer, just one line for each steps) ?
I know there can be multiples ways, but what is the most common backbone step strategy to create elements.
Thanks in advance.
I'm not 100% sure I understood you correctly. If I didn't please let me know in the comments.
There seems to be some confusion in your question regarding the usage of Backbone.Router in general. When the router maps a route to URL fragment #contacts, that has nothing to do with a DOM element with the id #contacts. The hash sign simply happens to be the identifier for an URL fragment and id CSS selector, but that's where the similarity ends.
Typically my router looks something like this:
var AppRouter = Backbone.Router.extend({
routes: {
contacts: "contactList"
},
contactList: function() {
var contacts = new ContactCollection();
var view = new ContactListView({collection:contacts});
view.render().$el.appendTo("#contacts");
}
});
Notice that the #contacts element doesn't need to be called that. You can call it #pony, or you can render the view directly to the document body if you want.
So in these terms the workflow is:
Router gets hit
Collection is initialized
View is rendered
Usual way i do is
Have the div#contacts loaded within body
Router maps the #contacts to the method showContacts in the router
showContacts creates the view, attaches it to the desired div
var view = new contactsView();
$('#contacts').empty().append(view.el);
view.render();
You need not define the id in the definition of contactsView

How do I avoid repetition when passing variables from the Controller/Action to the Layout

I am currently working on a project developed using Zend Framework, based on the structure of my web page design I have reached a point where I have to pass a small number of variables to my layout from each Controller/Action. These variables are:
<?php Zend_Layout::getMvcInstance()->assign('pageId', 'page1'); ?>
<?php Zend_Layout::getMvcInstance()->assign('headerType', '<header id="index">'); ?>
The reason for passing this information is firstly, I pass the page id as the multi column layout may change depending on the content being displayed, thus the page id within the body tag links the appropriate CSS to how the page should be displayed. Secondly I display a promotional jQuery slider only on the index page, but I need the flexibility to have it displayed on potentially multiple pages in case the wind changes and the client changes their mind.
My actual question: Is there a more appropriate method of passing this information to the Layout that I am overlooking?
I am not really questioning whether the information has to be sent, rather is there some Zend Framework feature that I have, in my haste, overlooked which would reduce the amount of repetitive redundant code which may very well be repeated in multiple Actions within the same controller?
You could turn that logic into an action helper than you can call from your controllers in a more direct way. You could also make a view helper to accomplish the same thing but view helpers usually generate data for the view rather than set properties.
// library/PageId.php
class Lib_PageId extends Zend_Controller_Action_Helper_Abstract
{
public function direct($title, $pageId, $headerType)
{
$view = $this->getActionController()->view;
$view->headTitle()->append($title);
$view->pageId = $pageId;
$view->headerType = $headerType;
}
}
In your controller actions you can now do this:
$this->_helper->PageId('Homepage', 'page1', 'index');
// now pageId and headerType are available in the view and
// Homepage has been appended to the title
You will also need to register the helper path in your Bootstrap like this:
protected function _initActionHelpers()
{
Zend_Controller_Action_HelperBroker::addPrefix('Lib');
}
Doing it like that can reduce the amount of repetitive code and remove needing to assign the values from the view. You can do it in the controller very quickly. You can also have default values in the case that the helper hasn't been called.
You shoudn't really be passing anything from the view to the layout, for a start the view should be included IN the layout, not the other way around.
So, setting your page title should be done using similar code to what you have, but inside the controller action being called:
$this->view->headTitle()->append('Homepage');
And the other two issues - you need to rethink as I stated to begin with. Maybe you're misunderstanding the layout/view principle? If you include the different views per action, then you simply change the div id when needed, and include the header for your banner only in the index.phtml file.