Manual:Intro:Patterns:Singleton (Legacy)
This version of our Learning Center is unmaintained.
This article may be out-of-date or contain incorrect information.
Please visit the new Sencha Learning Center for up-to-date material.
From Sencha - Learn
Contents |
Definition
A Singleton is a programming design pattern where only one instance of an object can be created within an application. You could think of a Singleton as a global variable that is defined once and available everywhere within your application.
The Singleton pattern is used throughout the Ext example code, however the reason for choosing this pattern is not always obvious from the examples alone. A typical Ext example consists of a Singleton with an "init" method that is called only once. In such an example, the Singleton is not really necessary. However if you were to add, for example, a "reload" method you might see how that could be called again from various places within your application. By using a Singleton, it ensures there is one and only one instance of a particular window control and you can access or change it's parameters from anywhere within the application.
Singleton object.
Sample code
Singleton = function(){ var _instance = null; return { getInstance : function(){ if(_instance === null){ _instance = {}; //define your instance here } return _instance; } }; }(); Ext.onReady(function(){ var x = Singleton.getInstance(); var y = Singleton.getInstance(); if(x == y){ alert("Objects are the same instance"); } });
Singleton object which extends an existing class
Sample code
myObservableSingleton = function(){ var privateProperty = "Only accessible internally"; function privateMethod() { alert("Only callable internally"); } return Ext.apply(new Ext.util.Observable, { publicProperty: "You can access this", publicMethod: function() { alert("You can call this"); } }) }();

English