Class Index | File Index

Classes


Class $class.descriptor.singleton_config

This is a fake class to document the configuration object for use with $class.descriptor#$singleton to setup a class as a singleton. If the defaults are acceptable, you can simply provide a value of true instead of a singleton config object.


Defined in: class-debug.js.

Class Summary
Constructor Attributes Constructor Name and Description
 
Field Summary
Field Attributes Field Name and Description
 

A function that is used to create the singleton instance.

Class Detail
$class.descriptor.singleton_config()
Field Detail: createInstance
{Function} createInstance

A function that is used to create the singleton instance. This function receives no arguments and is expected to return an instance of the class. The function is called within the context of the class/constructor. Defaults to a function that simply instantiates the class with no constructor arguments.

This property is useful for when you want to have a singleton, but it needs be instantiated with "dynamic static data"; data that is determined by the server so that it cannot be hard-coded in the JavaScript, but the data never changes during the lifetime of the script, so it is static as far as the script is concerned.

Defaults to a function that simply instantiates the class with the same arguments.

Warning:

If you think you want to do something like this, chances are that you really shouldn't be creating a singleton. This pattern of initializing a singleton with "dynamic static data" should only be used if the purpose of the class inherently makes the design require that there never be more than one instance, because multiple instances would catastrophically interfere with each other or other data. See also the warning about $class.descriptor#$singleton.

Example:

$class("Example", {
  $singleton: {
    createInstance: function() {
      // A default value allows the code to not depend on an externally 
      // defined value 
      var paramValue = this.DEFAULT_PARAM_VALUE;
      
      // If a global variable "EXAMPLE_PARAM_VALUE" exists, use its value.
      // The value of this variable could have been rendered by server 
      // code (PHP, JSP, etc). This allows default behavior/configuration
      // to be overridden if desired.
      if (typeof EXAMPLE_PARAM_VALUE != "undefined") {
        paramValue = EXAMPLE_PARAM_VALUE;
      }      
      
      return new this(paramValue);
    },
  },
  
  $constructor: function(param) {
    this._param = param;
  },
  
  getParam: function() {
    return this._param;
  },
  
  DEFAULT_PARAM_VALUE: $static(10)
});

var EXAMPLE_PARAM_VALUE = 5;
alert(Example.getInstance().getParam()); // alerts "5"

EXAMPLE_PARAM_VALUE = 20;
alert(Example.getInstance().getParam()); // still alerts "5"


Documentation generated by JsDoc Toolkit 2.3.2 on Sat Nov 13 2010 01:18:48 GMT-0500 (EST)