eventingLibrary

Written on September 5, 2019

문제

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) {
  obj.on = (name, cb) => {
    if (obj[name]) {
      obj[name] = obj[name].concat([cb.bind(obj)]);
    } else {
      obj[name] = [].concat([cb.bind(obj)]);
    }
  };
  obj.trigger = (name, ...args) => {
    if (obj[name]) {
      obj[name].forEach(func => func(...args));
    }
  };
  return obj;
};

👩🏻‍💻 배우는 것을 즐기는 프론트엔드 개발자 입니다
부족한 블로그에 방문해 주셔서 감사합니다 🙇🏻‍♀️

in the process of becoming the best version of myself