뒤로
준프
준프 ·

이벤트 버스로 결합도를 낮추기

이번에 소개해드리는 글은 '이벤트 버스'와 관련된 글입니다. 특히 이벤트 버스를 활용해 불필요한 결합을 제거하는 방법을 소개하고 있습니다. 특히 리액트 예시가 눈길을 끌었습니다.

이벤트 버스라는 단어가 잘 와닿지 않을 수도 있는데요, 가장 간단한 예시로 'input' 이벤트가 있습니다.

// HTML
<label for="nameInput">이름</label>
<input type="text" id="nameInput" />

// javascript
const $input = document.querySelector('#nameInput');

$input.addEventListener('input', (event) => {
  console.log('이름이 바뀌었어요 !', event.target.value);
});

input에 텍스트를 입력하면 브라우저에선 이벤트를 발생시킵니다. 이 과정은 텍스트 입력이라는 승객을 브라우저라는 버스에 태운 것으로 해석할 수 있습니다. 그리고 브라우저는 승객을 이벤트의 형태로 이벤트 리스터 정착지에 내려줍니다.

이 과정은 브라우저에서 기본으로 제공하는 버스라면 우리가 버스를 만들 수도 있는데요, 이 글에선 우리가 만드는 버스를 통해 프론트엔드에서 결합도를 낮추는 방법을 소개하고 있습니다. 이 글에선 아래와 같은 버스를 소개하고 있습니다.

let model = {
  value: '',
  set(val) {
    if (val === this.value) return
    this.value = val
    window.dispatchEvent(new CustomEvent('modelUpdate', { detail: this }))
  },
}

그리고 이벤트 버스를 사용했을 때 장점과 단점도 소개하고 있습니다.

An event bus allows us to loosen the coupling between the two parts of the code. By loosening the coupling between the code, we gain the ability to replace one part without affecting the other, which means the software becomes easier to modify. At least in theory.
...
A disadvantage of this indirect way of communicating is that it’s more difficult to identify who is being called or who is doing the calling or even if there are any callers or callees to begin with (because that’s what gives it the advantages).

사실 우리가 이벤트 리스너를 사용했을 때 장점과 단점을 기억해보면 이해하기 쉬울 거 같습니다.

제 경우 정확히 기억이 나진 않지만 커스텀 이벤트를 통해 문제를 해결했던 경험이 2-3회 정도 있었는데요, 알아두면 언젠가 도움이 되지 않을까 합니다.

0

댓글

로그인 후 댓글을 남길 수 있습니다.

하영진
하영진

오늘도 재밌는 내용 감사합니다 준프님 ㅎㅎ

준프
준프

감사합니다 ! :)