Classes in UI5
How to extend sap.ui.base.Object
So here’s a very basic template for extending the sap.ui.base.Object.
sap.ui.define([
"sap/ui/base/Object",
"sap/base/Log"
], function (Object, Log) {
"use strict";
return Object.extend("XXX.control.XXX", {
/**
* @class XXX
* @summary Example of an sap.ui.base.Object
*/
constructor: function (oController) {
this._oParentController = oController;
this._oServiceModel = oController.getView().getModel();
Log.info("Object initialized");
},
/**
* @memberOf XXX
* @description getXXX
*/
getXXX: function () {
},
/**
* @memberOf XXX
* @description setXXX
*/
setXXX: function () {
}
});
});
I always pass the “this” context in the constructor to get access to the servicemodels and other stuff.
this._oParentController = controller || void 0;
Aswell most of the times I only use one servicemodel so I also declare it in the constructor.
this._oServiceModel = this._oParentController.getModel();
Example
/control/Person.js
sap.ui.define([
"sap/ui/base/Object",
"sap/base/Log"
], function (Object, Log) {
"use strict";
return Object.extend("XXX.control.Person", {
/**
* @class Person
* @summary Example of an sap.ui.base.Object
* @param {Object} oController - this
* @param {Object} oArguments - Arguments
* @param {string} oArguments.name - Name of Person
*/
constructor: function (oController, oArguments) {
this._oParentController = oController;
this._oServiceModel = oController.getView().getModel();
this._oArguments = oArguments;
Log.info("Person initialized");
},
/**
* @memberOf Person
* @description Get Name
*/
getName: function () {
return this._oArguments.name;
},
/**
* @memberOf Person
* @description Set Name
* @param {string} sName - Name of the Person
*/
setName: function (sName) {
this._oArguments.name = sName;
}
});
});
/controller/XXX.controller.js
sap.ui.define([
"./BaseController",
"XXX/control/Person"
], function (BaseController, Person) {
"use strict";
onInit: function () {
this.oMax = new Person(this, {
name: "Max"
});
console.log(this.oMax.getName());
this.oMax.setName("Maxos");
console.log(this.oMax.getName());
}
That’s it. If you are interested in a real example:
Comments
Post a Comment