From 7f0ac04db59cb290961bd77a4e0d18cffd248151 Mon Sep 17 00:00:00 2001 From: Bryce Johnson Date: Fri, 30 Sep 2016 17:30:21 +0200 Subject: [PATCH 1/2] Document convention for singleton use in front-end code. --- doc/development/frontend.md | 49 +++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) 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]. From 2159c8792b289bb27f9947fb834fbd497efeeb28 Mon Sep 17 00:00:00 2001 From: Bryce Johnson Date: Tue, 1 Nov 2016 20:40:01 +0100 Subject: [PATCH 2/2] Fix spacing in code sample. --- doc/development/frontend.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/doc/development/frontend.md b/doc/development/frontend.md index 735b41314ef..c6aafc926ee 100644 --- a/doc/development/frontend.md +++ b/doc/development/frontend.md @@ -227,14 +227,15 @@ class MyThing { gl.MyThing = new MyThing(); // best + let singleton; class MyThing { constructor() { if (!singleton) { - singleton = this; - singleton.init(); - } + singleton = this; + singleton.init(); + } return singleton; } @@ -246,6 +247,7 @@ class MyThing { } gl.MyThing = MyThing; + ``` ## Supported browsers