53 lines
1.2 KiB
JavaScript
53 lines
1.2 KiB
JavaScript
const React = require('react');
|
|
const Store = require('./Store.js');
|
|
|
|
// "react-redux connect()"-like example
|
|
class StoreListener extends React.Component
|
|
{
|
|
componentDidMount()
|
|
{
|
|
Store.on(this.update);
|
|
}
|
|
|
|
componentWillUnmount()
|
|
{
|
|
Store.un(this.update);
|
|
}
|
|
|
|
update()
|
|
{
|
|
var newState = this.mapStateToProps(Store.data);
|
|
for (var i in newState)
|
|
{
|
|
if (this.state[i] != newState[i])
|
|
{
|
|
this.setState(newState);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
render()
|
|
{
|
|
var props = { ...this.initial, ...this.props, ...this.state };
|
|
return React.createElement(this.wrappedComponent, props);
|
|
}
|
|
}
|
|
|
|
module.exports = function(component, map, initial)
|
|
{
|
|
var cl = class extends StoreListener
|
|
{
|
|
constructor(props, context, updater)
|
|
{
|
|
super(props, context, updater);
|
|
this.wrappedComponent = component;
|
|
this.mapStateToProps = map;
|
|
this.initial = initial;
|
|
this.state = map(Store.data);
|
|
this.update = this.update.bind(this);
|
|
}
|
|
};
|
|
return cl;
|
|
};
|