Skip to content

Instantly share code, notes, and snippets.

@jpbecotte
Last active September 21, 2018 14:58
Show Gist options
  • Save jpbecotte/8f35e394ed447bdeaf9f92753a2913fc to your computer and use it in GitHub Desktop.
Save jpbecotte/8f35e394ed447bdeaf9f92753a2913fc to your computer and use it in GitHub Desktop.
What the heck is doing this code?
const transform = (object, props) => {
  const x = {
    original: { ...object },
    observers: [],
  };
  props.forEach(prop => {
    Object.defineProperty(x, prop, {
      configurable: false,
      enumerable: true,
      get() {
        console.log('Get -->', prop);
        return x.original[prop];
      },
      set(newValue) {
        console.log('Set -->', prop);
        x.original[prop] = newValue;
        x.observers.filter(o => o.prop === prop).forEach(observer => observer.fn(newValue));
      },
    });
  });
  return x;
};

const observe = (object, prop, fn) => {
  object.observers = [
    ...object.observers,
    { prop, fn },
  ];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment