Last active
March 10, 2019 16:56
-
-
Save mseddon/a1f2d9533c1e2f76a07b9e19b0d5cd06 to your computer and use it in GitHub Desktop.
Simple observer class decorator for preact and nx-js/observer-util.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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