• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    해결됨

storage를 동적으로 변경하는 경우 코드 변경 사항 문의드립니다.

23.01.14 10:28 작성 조회수 258

0

안녕하세요.

storage를 동적으로 변경하는 경우 현재 기준으로 어떤 부분의 코드를 변경하는 것이 좋을지 문의드립니다.

현재 코드에서는 아래와 같이 정적인 데이터(storage.js)를 main.js에서 주입해주는데요.

// main.js

import Store from "./store.js";
import storage from "./storage.js";

function main() {
  const store = new Store(storage);
  new Controller(store, views);
}

만약 storage 데이터를 ajax를 통해 동적으로 받아온다면, main.js와 Controller.js는 그대로 두고 Storage.js와 storage.js 파일만 변경하면 되나요?

즉, 아래 코드 주석처럼 하면 될까요? 또한, AJAX 요청은 Controller와 Storage 중 어느 부분에 작성하는 것이 일반적인가요?

// Controller.js
// 변경 없음

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

    this.searchFormView = searchFormView;
    this.searchResultView = searchResultView;
    this.subscribeViewEvents();
  }

  subscribeViewEvents() {
    this.searchFormView
      .on("@submit", (event) => this.search(event.detail.value)) //
  }

  search(searchKeyword) {
    this.store.search(searchKeyword);
  }

}
// storage.js
// 데이터를 빈 배열로 변경

const storage = {
  keywordData: [],
  historyData: [],
  productData: [],
};

export default storage;
// Store.js

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

    this.storage = storage;

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

  search(keyword) {
    this.searchKeyword = keyword;
    this.searchResult = // 여기서 AJAX 요청을 통해 storage.js의 상태 관리? 아니면 Controller에서 AJAX 요청?
 
  }
}

답변 1

답변을 작성해보세요.

0

수업에서 사용한 코드는 정적인 데이터인 storage를 사용하는데 이걸 외부 스토리지를 사용하신다는 말씀같아요. 그래서 xhr로 데이터를 가져오고 변경, 추가하는 작업도 하시려는거죠?

그러면 기존의 동기코드를 모두 비동기로 바꾸어야합니다. 함수를 호출한 결과를 바로 사용하는 것이 아니라 콜백을 전달해서 비동기 작업이 완료되었을때 콜백의 인자로 받는 방식이 되어야 할 거에요.

store.search(keyword, function handleSearch(result) { /* result에 결과가 담길 것이다. */ });

프라미스나 어싱크 함수를 사용할수도 있고요.

const result = await store.search(keyword); // search 함수가 프라미스를 반환합니다.