-
-
Save Kevnz/6051091 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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! | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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