Dear UI5 Developers,
In UI5 you can create classes and use objects as explained in these blogs:
UI5 Classes and objects - Inheritance
UI5 Classes and Objects - Putting it all together
In this blog I'm going to show you how the Singleton pattern can be used in UI5. This example is based on the example of the latest blog: UI5 Classes and Objects - Putting it all together
Singleton can be used as a shared controller to store global values like for example your JSON models. I often use it to implement AJAX calls to the backend.
To implement a singleton in UI5 you have to create a basic class. Instead of returning this class, you have to return a function that creates an instance of your Singleton class. This function will only make a new object/instance of the class the first time (if no instance/object exists) . To know if an instance/object is already created, you can use a global variable to keep the active object/instance.
In our example the Singleton will be used to create an object of the Person class. It will also have a function to add skills to a person. Last but not least it will also have a function to create an initial skill.
It will look like this:
sap.ui.define([ "sap/ui/base/Object", "be/wl/objects/model/Person", "be/wl/objects/model/Skill" ], function(Object,Person,Skill) { "use strict"; var instance; var services= Object.extend("be.wl.objects.model.services",{ constructor:function(){ this.person = {}; this.skill = {}; }, setPerson:function(firstname,lastname){ this.person = new Person({firstname:firstname,lastname:lastname}); }, newSkill:function(skill){ this.person.addSkill(skill); }, getInitialSkill:function(){ this.skill = new Skill({name:"name",value:"value"}); return this.skill; } }); return { getInstance: function () { if (!instance) { instance = new services(); } return instance; } }; });
Now you can use the singleton in your full UI5 project with the following syntax:
services.getInstance()
I've update the viewcontroller to use the singleton class, it will look like this:
onInit:function(){ services.getInstance().setPerson("Wouter","Lemaire"); this.getView().setModel(services.getInstance().person.getModel(),"person"); this.resetSkill(); }, addSkill: function() { services.getInstance().newSkill(services.getInstance().skill); this.resetSkill(); }, resetSkill:function(){ this.skill = services.getInstance().getInitialSkill(); this.getView().setModel(this.skill.getModel(),"skill"); }
The function setPerson will create an object of the Person class. We can access all properties of the singleton instance:
services.getInstance().person
The function newSkill will add a skill to the peron object and the function getInitialSkill will create an empty Skill object.
The result will look the same as in the blog UI5 Classes and Objects - Putting it all together but now it's using a singleton class.
You can find the full code example on plunker:
http://plnkr.co/edit/7y8FBnyRZLZDvnd2oIFS?p=preview
Kind regards,
Wouter