Welcome to mirror list, hosted at ThFree Co, Russian Federation.

design_patterns.md « fe_guide « development « doc - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ffca801fd03e1aa073eccda1e70980bc963e640e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# Design Patterns

## Singletons

As with everything at GitLab, the simplest approach should be taken.
Below we have defined a few patterns to achieve singleton-like behaviour.
Pick the simplest one that fits your usecase.

```javascript
const MyThing = {
  prop: 'hello',
  init: () => {}
};

export default MyThing;
```

```javascript
class MyThing {
  constructor() {
    this.prop = 'hello';
  }
  init() {}
}

export default new MyThing();
```

```javascript

export default class MyThing {
  constructor() {
    if (!this.prototype.singleton) {
      this.init();
      this.prototype.singleton = this;
    }
    return this.prototype.singleton;
  }

  init() {
    this.prop = 'hello';
  }

  method1() {}
}

```

## Manipulating the DOM in a JS Class

When writing a class that needs to manipulate the DOM guarantee a container option is provided.
This is useful when we need that class to be instantiated more than once in the same page.

Bad:
```javascript
class Foo {
  constructor() {
    document.querySelector('.bar');
  }
}
new Foo();
```

Good:
```javascript
class Foo {
  constructor(opts) {
    document.querySelector(`${opts.container} .bar`);
  }
}

new Foo({ container: '.my-element' });
```
You can find an example of the above in this [class][container-class-example];


[container-class-example]: https://gitlab.com/gitlab-org/gitlab-ce/blob/master/app/assets/javascripts/mini_pipeline_graph_dropdown.js