Dojo Singleton or at least a static method / variable?

Does anyone know how to make a Dojo singleton class, or at least how to create a static method or variable in a Dojo class?

I am currently achieving this by having a global variable for each class and a method that sets this variable if its value is null, but this is a crappy solution. Having a singleton class would be a lot nicer because you could inherit it, and voilá has a singleton :)

Heinrich

+5
source share
9 answers

dojo.declareClass , new . Java , JavaScript . , Java- JavaScript.

, :

if (typeof dojo.getObject('x.y.z') === 'undefined') {
    dojo.setObject('x.y.z', {
       //object definitions
    });
}

, dojo.

dojo.declare("x.y.ABC", {});
x.y.ABC.globalV = 'abc';

dojo.require JavaScript dojo, .

+7

JavaScript :
http://kaijaeger.com/articles/the-singleton-design-pattern-in-javascript.html

Dojo -tize , 1.7+, , , , , , , ...

, - , , . Dojo, "" ( Dojo), ...

MakeSingleton.js

define(['dojo/_base/lang'], function(lang)
{
  return function(ctor) {   // not defining a class, just a utility method.
      var singletonCtor,    // our singleton constructor function.
          instance = null;  // singleton instance provided to any clients.

      // define the singleton constructor with accessor method.
      // (captures 'ctor' parameter and 'instance' variable in a function
      //  closure so that they are available whenever the getInstance() method
      //  on the singleton is called.)
      singletonCtor = new function() {       // note: 'new' is important here!!
          this.getInstance = function() {    // our accessor function
              if (!instance) {               // captures instance in a closure
                instance = new ctor();       // create instance using original ctor.
                instance.constructor = null; // remove instance constructor method
              }                              //  so you cannot use new operator on it!!
              return instance;               // this is our singleton instance.
          }  
      };  

      // Since we are working with Dojo, when declaring a class object, if you
      // provide a 'className' as the first parameter to declare(...), Dojo will
      // save that value in the 'declaredClass' property on the object prototype...
      // ... and adds a reference to that constructor function in the global namespace
      // as defined by the 'className' string.
      //
      // So if 'declaredClass' has a value, we need to close the hole by making
      // sure this also refers to the singleton and not the original constructor !!
      //
      if (ctor.prototype && ctor.prototype.declaredClass) {
        lang.setObject(ctor.prototype.declaredClass, singletonCtor);
      }

      // return the singleton "constructor" supports only a getInstance() 
      // method and blocks the use of the 'new' operator.
      return singletonCtor;

  }; // return "MakeSingleton" method
};  // define(...)

, Dojo 1.7+, Singleton? , ...

MySingletonClass.js

define(['dojo/_base_declare', 'MakeSingleton'], 
       function(declare, MakeSingleton)
{
    return MakeSingleton( declare('MySingletonClass', [...], {
                          // Define your class here as needed...
                        }));  
});

... declare (...) MakeSingleton (...) , (Function), Dojo, , "className" declare (...), MakeSingleton , , . , singleton ( MakeSingleton), Dojo factory. , ...
.

, ... "className", , - . "className", (, ), ( , Dojo , ).

MakeSingleton.js - , , getInstance(). getInstance() . "" singleton, . "" (if "className" ), . . - singleton getInstance().

SomeOtherModule.js

define(['dojo/_base/declare', 'MySingletonClass'],
       function(declare, MySingletonClass) 
{
    return declare(null, { 
        mySingleton: null,    // here we will hold our singleton reference.
        constructor: function(args) {
            ...
            // capture the singleton...
            mySingleton = MySingletonClass.getInstance();
            ... 
            mySingleton.doSomething(...);
        };

        mySpecialSauce: function(...) {
            mySingleton.doSomethingElse(...);
        };

        moreSauce: function(...) {
            var x;
            x = MySingletonClass.getInstance(); // gets same instance.
            x = new window.MySingletonClass();  // generates an error!!
            x = new MySingletonClass();         // generates an error!!
            // Dojo loader reference generates an error as well !!
            x = new require.modules['MySingletonClass'].result(); 
        };
    });
});

, , , script .. Singleton, , "" .

+14
require(["dojo/_base/declare"], function (declare) {
var o =
    declare("com.bonashen.Singleton", null, {
        say : function (name) {
            console.log("hello," + name);
        }
    });
//define static getInstance function for com.bonashen.Signleton class.
console.debug("define getInstance function. ");
o.getInstance = function () {
    if (null == o._instance)
        o._instance = new o();
    return o._instance;
};});
+8

, dojo 1.7+ AMD ( ) :

define([
    "dojo/_base/declare",
], function(
    declare
) {
    var SingletonClass = declare("SingletonClass", [], {
        field: 47, 
        method: function(arg1) {
            return field*5;
        }
    });
    if (!_instance) {
        var _instance = new SingletonClass();
    }
    return _instance;
});

, .

+8

, :

define(['dojo/_base/declare'], function (declare) {

    var singletonClass = declare(null, {

        someProperty: undefined,

        constructor: function () {
           if (singletonClass.singleton)
              throw new Error('only one instance of singletonClass may be created');

           this.someProperty = 'initial value';
        }
     });

     // create the one and only instance as a class property / static member
     singletonClass.singleton = new singletonClass();

     return singletonClass;
});

:

define(["app/singletonClass"], function(singletonClass) {
    var instance = singletonClass.singleton;  // ok
    var newInstance = new singletonClass();   // throws Error
});
+3

Dojo? () ?

:

:

define(["dojo/_base/declare"], function(declare){
var TestApp = declare(null, {
    constructor: function(){
        console.log("constructor is called only once");
        this.key = Math.random();
        console.log("generated key: "+this.key);
    },
    sayHello : function(){
        console.log("sayHello: "+this.key);
    }
});
return new TestApp();
});

:

    <script>
    require(['simplemodule.js'], function (amodule) {
        amodule.sayHello();
        console.log("first require");
    });

    require(['simplemodule.js'], function (amodule) {
        amodule.sayHello();
        console.log("second require");
    });


    require(['simplemodule.js'], function (amodule) {
        amodule.sayHello();
        console.log("third require");
    });

</script>

:

constructor is called only once simplemodule.js:4
generated key: 0.6426086786668748 simplemodule.js:6
sayHello: 0.6426086786668748 simplemodule.js:9
first require test.html:15
sayHello: 0.6426086786668748 simplemodule.js:9
second require test.html:20
sayHello: 0.6426086786668748 simplemodule.js:9
third require 
+3

javascript . - , :

something.myObject = something.myObject || {
    //Here you build the object
}

, something.myObject, , ( ||) {}. , , .

+2

Dojo:

var makeSingleton = function (aClass) {
    aClass.singleton = function () {
        var localScope = arguments.callee;
        localScope.instance = localScope.instance || new aClass();
        return localScope.instance;
    };
    return aClass;
};

makeSingleton(dojo.declare(...));

, :

myClass.singleton()
+1

(Dojo 1.10), .

A good article on this topic can be found here .

define([

], function (

    ) {
    'use strict';
    var _instance;
    function _SingleTone() {
    }
    _SingleTone.prototype = {
        init: function () {
        }
    };
    return function _getSingleton() {
        return (_instance = (_instance || new _SingleTone()));
    };
});
+1
source

All Articles