likeopera-frontend/StoreListener.js

40 lines
1.0 KiB
JavaScript

const React = require('react');
const Store = require('./Store.js');
// "react-redux connect()"-like example
var StoreListener = React.createClass({
componentDidMount: function()
{
Store.on(this.update);
},
componentWillUnmount: function()
{
Store.un(this.update);
},
update: function()
{
var newState = this.props.mapStateToProps(Store.data);
for (var i in newState)
{
if (this.state[i] != newState[i])
{
this.setState(newState);
return;
}
}
},
getInitialState: function()
{
return { ...this.props.initial, ...this.props.mapStateToProps(Store.data) };
},
render: function()
{
return React.createElement(this.props.wrappedComponent, this.state);
}
});
module.exports = function(component, map, initial)
{
return React.createElement(StoreListener, { wrappedComponent: component, mapStateToProps: map, initial: initial||{} });
};