Skip to content

Instantly share code, notes, and snippets.

@treshugart
Created October 27, 2017 03:07
Show Gist options
  • Save treshugart/f5e7e36860b5c105f06e2054cfcab852 to your computer and use it in GitHub Desktop.
Save treshugart/f5e7e36860b5c105f06e2054cfcab852 to your computer and use it in GitHub Desktop.
import { autorun, toJS } from 'mobx';
import { props } from 'skatejs';
export const withObserver = (Base = HTMLElement) =>
class extends Base {
constructor() {
super();
const { stores } = this;
// This dynamically adds props post construction, so this happens for every instance that is created. One way to
// make this more efficient is to allow for this as an edge case, but to use staticially defined stores on the
// class instead.
Component.props = Object.keys(stores).reduce((prev, curr) => {
prev[curr] = props.array;
return prev;
}, {});
// Define an updater for each store. Doing this separately for each store ensures that if one store is updated,
// the others aren't triggered.
Object.keys(stores).forEach(key => {
autorun(() => (this[key] = toJS(stores[key].items)));
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment