Skip to content

Instantly share code, notes, and snippets.

@kara-ryli
Created July 8, 2011 20:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kara-ryli/1072689 to your computer and use it in GitHub Desktop.
Save kara-ryli/1072689 to your computer and use it in GitHub Desktop.
Create a singleton class in YUI3. This class can only be instantiated one time. All later instantiations return references to the original.
YUI().use("singleton-class", function (Y) {
var instance1 = new Y.SingletonClass(),
instance2 = new Y.SingletonClass();
Y.log(instance1 === instance2); // true!
window.instance1 = instance1;
});
YUI().use("singleton-class", function (Y) {
var instance3 = new Y.SingletonClass();
Y.log(window.instance1 === instance3); // true!
});
YUI.add("singleton-class", function (Y) {
var GlobalEnv, SingletonClass, instanceMethods, classMethods;
// create your own namespace in the YUI global environment
GlobalEnv = YUI.namespace("Env.SingletonClassNamespace");
// define the singleton class
SingletonClass = function (confg) {
// if an instance doesn't exist yet
// do the normal class initialization and set the global
// instance to this instance
if (Y.Lang.isUndefined(GlobalEnv.instance)) {
SingletonClass.superclass.constructor.apply(this, arguments);
GlobalEnv.instance = this;
}
// instead of returning this, return the global instance
return GlobalEnv.instance;
};
// expose your singleton class to the world
Y.SingletonClass = SingletonClass;
// if an instance of the class already exists, you don't
// even need to do anything else. This doesn't
// work if your application relies on class methods, so
// only uncomment this if adding instance and class methods
// to your class is expensive (it's probably not).
//
// if (! Y.Lang.isUndefined(GlobalEnv.instance)) {
// return;
// }
// add your instance methods with at least these two defined
instanceMethods = {
initializer: function (config) {},
destructor: function () {}
};
// add your class methods with the NAME and ATTRS properties
classMethods = {
NAME: "singleton-class",
ATTRS: {
foo: {
value: "bar"
}
}
};
// add instance methods, class methods and attrs by extending Y.Base
Y.extend(SingletonClass, Y.Base, instanceMethods, classMethods);
}, "3.3.0", { requires: ["base-base"] });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment