Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ES6 Classes w/Mixins -- Idea -- React 0.13
export function ComponentWithMixins( ...mixins) {
class MixedComponent extends React.Component { }
for( let mixin of mixins) {
// TODO: Would need to handle mixin collisions...
for( let name of Object.keys( mixin)) {
MixedComponent.prototype[ name]= mixin[ name]
}
}
return MixedComponent
}
// Can a form of simple mixins be supported via ES6 classes?
import {ComponentWithMixins} from './component-with-mixins'
let {PureRenderMixin, LinkedStateMixin}= React.addons
class MyView extends ComponentWithMixins( PureRenderMixin, LinkedStateMixin) {
render() {
return (
<div>
Hello
<input valueLink={ this.linkState( 'name')}/>
</div>
)
}
}
@mattmccray

This comment has been minimized.

Copy link
Owner Author

@mattmccray mattmccray commented Feb 17, 2015

The tricky part would be for mixins that hook into lifecycle events. We could keep a list of mixin lifecycle hooks, then add the appropriate methods to the prototype that would execute each one... ?

💧
🌱

Thoughts?

@achal7

This comment has been minimized.

Copy link

@achal7 achal7 commented Feb 22, 2015

We can implement the mixins by exposing the life cycle events i.e. ReactClassInterface
And within the ComponentWithMixin we can use the mixSpecIntoComponent of React
for( let mixin of mixins) {
for( let name of Object.keys( mixin)) {
mixSpecIntoComponent (Constructor, mixin);
}
}

I have wrote this code just to check weather i can achieve this or not, and it worked.
BUT still i think mutating existing component by adding extra behavior is not the one we should go for.
We should go for composition and also more functional behavior, since that is also one for the reason why i have chose react over Angular.
So think the Component as a context, and the life cycles as behaviors which carries the component along each way.
And the mixins declare the life cycle events asking for context as an argument, so we can avoid "this" from the mixins as well.

I will try to write prototype of above idea in coming days. Since then i can decouple the data/context from the life cycle events.

@mattmccray

This comment has been minimized.

Copy link
Owner Author

@mattmccray mattmccray commented Mar 6, 2015

Interesting. I'd be curious to see what you come up with.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.