Dear UI5 Developers,
In my previous blog I've talked about the basics of classes and objects in UI5:
Now I'll extend this with inheritance.
This example will use a parent class for creating the JSON model and will have a get function for the model. It extends from the sap.ui.base.Object class.
The constructor will set the current object as data for the model. The "getModel" function will be used to fetch the model.
Parent class:
sap.ui.define([ "sap/ui/base/Object", "sap/ui/model/json/JSONModel" ], function(Object,JSONModel) { "use strict"; return Object.extend("be.wl.objects.model.BaseObject", { constructor: function() { this.model = new JSONModel(); this.model.setData(this); }, getModel:function(){ return this.model; } }); });
If we want to use this class as parent for others classes we'll have to extend this class instead of extending "sap.ui.base.Object" . Besides extending the parent class, we'll also have to call the constructor of the parent in the contructor of the child. Therefore we use <name of parent class>.call(this).
See how I've changed the example of my previous blog to work with the parent class.
The constructor will call the constructor of the parent class: "BaseObject.call(this)"
sap.ui.define([ "be/wl/objects/model/BaseObject" ], function(BaseObject) { "use strict"; return BaseObject.extend("be.wl.objects.model.Person", { constructor: function(data) { BaseObject.call(this); if(data){ this.firstname = data.firstname; this.lastname = data.lastname; this.fullname = this.getFullName(); } }, getFullName:function(){ return this.firstname+" "+this.lastname; } }); });
I don't need to create the model in the constructor of my Person class and I don't need the function "getModel". This is done in the parent class. When creating an object of the class "Person" the object will also have the functions of the parent class.
The coding of the controller stays the same with or without parent class:
onInit:function(){ this.p = new Person({firstname:"Wouter",lastname:"Lemaire"}); this.getView().setModel(this.p.getModel(),"person"); }
All the properties of the object can be used in the view:
<Input value="{person>/firstname}" editable="false"></Input> <Input value="{person>/lastname}" editable="false"></Input> <Input value="{person>/fullname}" editable="false"></Input>
It will look the same as without the parent class:
You can find the full example on Plunker:
http://plnkr.co/edit/b1XmYA1wBxm6q0u3iRBx?p=preview |
See how you can put it all together:
UI5 Classes and Objects - Putting it all together
Kind regards,
Wouter