728x90

처음에 봤을 때 생소한 문제라서 의아했던 문제...

Make an eventing system mix-in that adds .trigger() and .on() to any input object.

이 조건으로 주어진 함수에 인자로 들어가는 obj에 해당하는 메소드를 생성하는 문제임을 이해했다.

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
/*
 * Make an eventing system mix-in that adds .trigger() and .on() to any input
 * object.
 *
 * Example usage:
 * var obj = mixEvents({ name: 'Alice', age: 30 });
 * obj.on('ageChange', function(){ // On takes an event name and a callback function
 *    console.log('Age changed');
 * });
 * obj.age++;
 * obj.trigger('ageChange'); // This should call our callback! Should log 'age changed'.
 *
 * Caveats:
 * - mixEvents should return the original object it was passed after extending it.
 * - If we repeatedly call .on with the same event name, it should
 *   continue to call the old function as well. That is to say, we can have multiple
 *   listeners for an event.
 * - If `obj.trigger` is called with additional arguments, pass those to the
 *   listeners.
 * - It is not necessary to write a way to remove listeners.
 */
 
var mixEvents = function (obj) {
  //mixEvents function의 input으로 들어오는 obj에 .trigger method, .on method를 추가해야함
  let eventObj = {}; //on메소드에 들어갈 콜백 함수들을 모아두는 객체?
 
  obj.on = function (eventName, callbackFunc) {
    if (eventObj[eventName] !== undefined) {
      //이미 추가한 이벤트라면?
      eventObj[eventName].push(callbackFunc);
    } else {
      eventObj[eventName] = [callbackFunc];
    }
  }; // 첫번째 인자로는 이벤트 명이, 두번째 인자로는 실행되어야할 어떠한 함수가 온다.
  obj.trigger = function (eventUse, ...params) {
    //첫번째 인자는 이벤트 명이, 두번째 인자부터는 정해지지 않은 변수들이 그때그때 들어오므로 rest parameter
    if (eventObj[eventUse] !== undefined) {
      eventObj[eventUse].forEach((cb) => {
        cb.call(obj, ...params);
      });
    }
  };
  return obj;
};
 
cs
Tip
rest parameter의 사용과 apply에 대한 적절한 이해가 필요한 문제
728x90

+ Recent posts