๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
JavaScript/Vanila

[Vanila js] ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ ๊ธฐ๋Šฅ ๊ตฌํ˜„

by ๐Ÿณ Laboon 2024. 7. 31.

View

export default class SearchResultView extends View {
    constructor() {
        super(qs("#search-result-view"));

        this.template = new Template();
    }

    show(data = []) {
        if (data.length > 0) {
            this.element.innerHTML = this.template.getList(data);
        } else {
            this.element.innerHTML = this. template.getEmptyMessage();
        }

        super.show();
    }
}

์ด๋ฒˆ์—๋Š” ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ ๊ตฌํ˜„์„ ์œ„ํ•ด ์ •์  ํŽ˜์ด์ง€์—์„œ search-result-view๋ฅผ ์ƒ์„ฑํ•˜๊ณ  query selector๋กœ ํ˜ธ์ถœํ•œ๋‹ค.

๊ทธ๋Ÿผ SearchResultView์˜ element ๋ณ€์ˆ˜๋Š” ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ ํƒœ๊ทธ์˜ ์ •๋ณด๋ฅผ ๊ฐ–๊ฒŒ ๋œ๋‹ค.

 

Template์€ class๋กœ ์–ด๋–ป๊ฒŒ ๋ Œ๋”๋ง ํ•  ๊ฒƒ์ธ์ง€์— ๋Œ€ํ•ด ๋ช…์‹œํ•ด๋‘” ์ฝ”๋“œ์ด๋‹ค.

์ฆ‰, Controller ์—์„œ์˜ ์ž‘์—…์„ ๋งˆ์น˜๊ณ  View์˜ show ๋ฉ”์„œ๋“œ๋กœ ๋ Œ๋”๋ง์„ ํ•  ๊ฒƒ์ž„์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.


Controller

export default class Controller {
  constructor(store, {searchFormView, searchResultView}) {
    this.store = store;
    this.searchFormView = searchFormView;
    this.searchResultView = searchResultView;
  }

์ถ”๊ฐ€๋กœ SearchResultView์— ๋Œ€ํ•œ ์˜์กด์„ฑ๋„ ์ถ”๊ฐ€ํ•ด์ค€๋‹ค.

 

์•ž์„œ ๊ฒ€์ƒ‰ ๊ธฐ๋Šฅ ๊ตฌํ˜„ํ•˜๊ธฐ์—์„œ ์ž‘์„ฑ๋œ, search()์™€ reset()์˜ ์„œ๋น„์Šค ๋กœ์ง์„ ์™„์„ฑํ•˜๋ฉด ๋œ๋‹ค.


Model

export default class Store {
  constructor(storage) {
    if (!storage) throw "no storage";

    this.storage = storage;
    this.searchResult = [];
    this.searchKeyword = "";
  }
}

searchKeyword์™€ searchResult๋ฅผ ๋‹ด์„ ๋ณ€์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด์ฃผ๊ณ  Business Logic์„ ์ž‘์„ฑํ•ด์ค€๋‹ค.


Quest

Q. reset ๊ธฐ๋Šฅ ๊ตฌํ˜„ํ•˜๊ธฐ

// controller
  reset() {
    this.store.reset();
    this.render();
  }
  
// model
  reset() {
    this.searchKeyword = "";
  }

๊ฐ•์‚ฌ๋‹˜์€ Controller reset() ๋ฉ”์†Œ๋“œ์— this.store.searchKeyword = ""๋ฅผ ์ถ”๊ฐ€ํ–ˆ๋‹ค.

๋‚˜๋Š” keyword๊ฐ€ Store ๋ผ๋Š” Model์— ์ข…์†๋œ ๋ณ€์ˆ˜์ด๋ฏ€๋กœ Store ๊ฐ์ฒด์—์„œ ์ง์ ‘ ์ ‘๊ทผํ•˜๋„๋ก ์ธ์Šคํ„ด์Šค ๋ฉ”์„œ๋“œ๋กœ ๋งŒ๋“ค์—ˆ๋‹ค.

์ถ”๊ฐ€๋กœ, ๊ฐ•์‚ฌ๋‹˜์€ searchResult ๋˜ํ•œ ๋นˆ ๋ฐฐ์—ด๋กœ ์ดˆ๊ธฐํ™”ํ•˜์˜€๋Š”๋ฐ, ๋‚˜๋Š” render() ์ž‘์—…์—์„œ searchResult๊ฐ€ update ๋˜๋ฏ€๋กœ ๊ตณ์ด ์ž‘์„ฑํ•˜์ง€๋Š” ์•Š์•˜๋‹ค.


Result

์‹คํ–‰๊ฒฐ๊ณผ


โ€ป ์ด์ „ Post์—์„œ์˜ ๊ถ๊ธˆํ–ˆ๋˜ ์  ํ•ด๊ฒฐ

Controller ์—์„œ Service ๋กœ์ง์„ ์ž‘์„ฑํ•œ๋‹ค.