Skip to content

Instantly share code, notes, and snippets.

@mseddon
Last active March 10, 2019 16:56
Show Gist options
  • Save mseddon/a1f2d9533c1e2f76a07b9e19b0d5cd06 to your computer and use it in GitHub Desktop.
Save mseddon/a1f2d9533c1e2f76a07b9e19b0d5cd06 to your computer and use it in GitHub Desktop.
Simple observer class decorator for preact and nx-js/observer-util.
import { observe, unobserve } from "@nx-js/observer-util";
export const observer = (klass) => {
let kp = klass.prototype,
cwm = kp.componentWillMount,
cdu = kp.componentDidUnmount;
kp.componentWillMount = function() {
this.render = observe(this.render, { scheduler: () => this.setState(), lazy: true })
cwm && cwm.apply(this, arguments);
}
kp.componentDidUnmount = function() {
unobserve(this.render);
cdu && cdu.apply(this, arguments);
}
return klass;
}
/// Example Usage
let thing = observable({ foo: "This is foo's data"});
@observer
class Foo extends Component {
render() {
return <h1>{thing.foo}</h1>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment