589.md 1.6 KB
Newer Older
Lab机器人's avatar
readme  
Lab机器人 已提交
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 78 79 80 81
# Design Patterns

> 原文:[https://docs.gitlab.com/ee/development/fe_guide/design_patterns.html](https://docs.gitlab.com/ee/development/fe_guide/design_patterns.html)

*   [Singletons](#singletons)
*   [Manipulating the DOM in a JS Class](#manipulating-the-dom-in-a-js-class)

# Design Patterns[](#design-patterns "Permalink")

## Singletons[](#singletons "Permalink")

当给定任务仅需要一个对象时,最好将其定义为`class`而不是对象文字. 除非灵活性很重要(例如,对于测试),否则也最好明确限制实例化.

```
// bad

const MyThing = {
  prop1: 'hello',
  method1: () => {}
};

export default MyThing;

// good

class MyThing {
  constructor() {
    this.prop1 = 'hello';
  }
  method1() {}
}

export default new MyThing();

// best

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

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

  method1() {}
} 
```

## Manipulating the DOM in a JS Class[](#manipulating-the-dom-in-a-js-class "Permalink")

在编写需要处理 DOM 的类时,请确保提供了一个容器选项. 当我们需要在同一页面中多次实例化该类时,这很有用.

Bad:

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

Good:

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

new Foo({ container: '.my-element' }); 
```

您可以在这上面的例子[](https://gitlab.com/gitlab-org/gitlab/blob/master/app/assets/javascripts/mini_pipeline_graph_dropdown.js) ;