inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

[React 1부] 만들고 비교하며 학습하는 React

[순수JS 1] 검색결과 1

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

해결된 질문

436

JIYEON KIM

작성한 질문수 4

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 요청?
 
  }
}

react MVC

답변 1

0

김정환

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

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

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

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

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

 

리액트 1,2부 이후 후속 강의나 준비 중인 다른 강의가 있으신가요?

1

90

2

super.show() 호출하는 이유가 궁금합니다.

1

81

2

class와 constructor를 이용한 객체 지향 프로그래밍

0

225

2

mvc 패턴 질문

0

197

2

Cannot read properties of undefined (reading 'props')

0

271

2

delegate, emit 필요한 이유

0

197

2

어떤거를 먼저 들어야 하는지 도와주세요

1

265

1

localhost:8080 접속 불가

1

282

1

최근검색어 3 풀이에서

1

188

1

import 문제

1

233

1

자동변환 관련

1

203

1

sort() 질문 드립니다.

1

304

2

reset 시점에 searchResult 빈 배열로 update

2

311

2

Button에 Onclick사용

1

248

1

npx lite-server error 확인 요청드립니다.

1

470

2

node 20이상 쓸때 꿀팁

4

760

3

디버깅 관련질문이 있습니다.

1

295

1

[순수JS2]탭 3(풀이) 질문있습니다.

1

229

1

추상화를 어떻게 받아들이면 될까요??

1

435

1

on 메서드 eventName 문의

1

268

1

import에 관해서 질문드립니다

1

256

1

view.js의 on 메소드에 대해 질문드립니다

1

260

1

componentDidMount에서 getKeywordList()를 하는 이유

1

243

1

[순수JS1]검색폼2_git branch 이동관련

1

281

1