summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBryce Johnson <bryce@gitlab.com>2016-09-30 17:30:21 +0200
committerBryce Johnson <bryce@gitlab.com>2016-10-31 19:28:15 +0100
commit7f0ac04db59cb290961bd77a4e0d18cffd248151 (patch)
tree19de041e133ac9457628b5414b54a1d1d179a2e4
parenta60cc42b262cb63ce5d2284f1f3f41d6521daa14 (diff)
downloadgitlab-ce-7f0ac04db59cb290961bd77a4e0d18cffd248151.tar.gz
Document convention for singleton use in front-end code.
-rw-r--r--doc/development/frontend.md49
1 files changed, 49 insertions, 0 deletions
diff --git a/doc/development/frontend.md b/doc/development/frontend.md
index 4fb56444917..735b41314ef 100644
--- a/doc/development/frontend.md
+++ b/doc/development/frontend.md
@@ -199,6 +199,55 @@ As long as the fixtures don't change, `rake teaspoon:tests` is sufficient
Please note: Not all of the frontend fixtures are generated. Some are still static
files. These will not be touched by `rake teaspoon:fixtures`.
+## Design Patterns
+
+### Singletons
+
+When exactly one object is needed for a given task, prefer to define it as a
+`class` rather than as an object literal. Prefer also to explicitly restrict
+instantiation, unless flexibility is important (e.g. for testing).
+
+```
+// bad
+
+gl.MyThing = {
+ prop1: 'hello',
+ method1: () => {}
+};
+
+// good
+
+class MyThing {
+ constructor() {
+ this.prop1 = 'hello';
+ }
+ method1() {}
+}
+
+gl.MyThing = new MyThing();
+
+// best
+let singleton;
+
+class MyThing {
+ constructor() {
+ if (!singleton) {
+ singleton = this;
+ singleton.init();
+ }
+ return singleton;
+ }
+
+ init() {
+ this.prop1 = 'hello';
+ }
+
+ method1() {}
+}
+
+gl.MyThing = MyThing;
+```
+
## Supported browsers
For our currently-supported browsers, see our [requirements][requirements].