Skip to content

Instantly share code, notes, and snippets.

@bionicbrian
Last active August 29, 2015 14:25
Show Gist options
  • Save bionicbrian/75d3854c00f188138e3a to your computer and use it in GitHub Desktop.
Save bionicbrian/75d3854c00f188138e3a to your computer and use it in GitHub Desktop.
Mixin Behaviors with React Lifecycle Hooks
var mixinBehavior = (behavior) => (target) => {
var componentDidMount = target.prototype.componentDidMount;
target.prototype.componentDidMount = function () {
componentDidMount.call(this);
behavior.onComponentDidMount(this);
}
}
class DraggableBehavior {
constructor(config) {
this.constraint = config.constraint;
}
onComponentDidMount(target) {
console.log("draggable componentDidMount. We have state, " + target.state.name);
}
}
class OtherBehavior {
onComponentDidMount(target) {
console.log("another behavior knows the component did mount");
}
}
@mixinBehavior(new OtherBehavior())
@mixinBehavior(new DraggableBehavior({ constraint: 4 }))
class Component {
constructor() {
this.state = { name: "Brian" };
}
componentDidMount() {
console.log("the real componentDidMount")
}
}
var c = new Component();
c.componentDidMount();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment