Ext JS - Learning Center

Manual:Intro:Patterns:Singleton

From Learn About the Ext JavaScript Library

Jump to: navigation, search
Summary: Patterns:Singleton
Author:
Published:
Ext Version: 1.1
Languages: en.png English fr.png French kr.png Korean

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");
        }
    })
}();
  • This page was last modified on 3 July 2008, at 14:21.
  • This page has been accessed 14,524 times.